Micha F. Micha F. - 2 years ago 70
Android Question

API - How can I let API-users declare their own types (which are then used by the API)?

I want to create a library (for own use to begin with but maybe for publishing later so I want to do it the proper way).

I'll use following (abstract) example to explain my question:

public void onSomeEvent(SomeEvent someEvent) {
String action = someEvent.getAction();

EventTypes eventTypes = getEventTypes(); //problem lies with this method

for (EventType eventType : eventTypes) {
if (eventType.getAction().equals(action)) {

private EventTypes getEventTypes {
//User should have defined his own event-type-classes by extending EventType:
//What is the best way to let the user list/define these EventTypes
//so my API can access them (e.g. with this method)?

My question is as shown in the comment of the example:

What is the best way to let the user of my API define his own EventTypes for this EventReceiver of the API while meeting (in best case all of the) following criteria:

  • event-types are easy to define for users

  • not using reflection

  • user-types are not registered at runtime, but statically listed somewhere (without annotation-processor)

I don't know if these creteria can all be fulfilled (I guess not).

But if you neglect one or more of the criteria (the first one shouldn't be in any case), please explain to me why there is no better way of doing it (without writing my own annotation-processor).

I hope my question is clear.

If you think it isn't, please suggest me how to make it more precise.

If you think I'm missing out something or should make an entirely different approach, I'd be glad for your corrections.

Thank you in advance.

Answer Source
    public List<? extends EventType> getEventTypes() {

Time to learn about Generics, my friend:

Lesson: Generics (Updated) (The Java Tutorials > Learning the Java Language)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download