Java Annotations for calling methods
I having a little trouble making use out of annotations in order to invoke the method that the annotation pertains to... I will give an example:
class MyEventHandlers {
@handler(id=“1”)
public doSomething() {
...
}
@handler(id=“2”)
public doSomethingElse() {
...
}
}
....
subscribe(“event1”, new MyEventHandlers, “1”);
//or maybe a better way to do this?!
....
//later, when I detect ‘event1’ I can process the required handler:
process(new MyEventHandlers, “1”)
The idea is, I want to have a way for 开发者_StackOverflowdefining handlers to events, and then linking a events to handlers. (consider for now an event is some string literal).
In all, I am not sure, what is the best style to use for doing what I want. The above is what I think at the moment. If there is better style to achieve this, please suggest.
I suspect that what you want to do, could be more easily implemented with an AOP framework.
But since you might want to do it yourself anyway:
The key to performance is to only use reflection during setup. So when subscribe
ing, you create a handler descriptor and add it to the listeners for the event. A handler descriptor is basically a java.lang.reflect.Method with an instance to call it on, and some knowledge on how to get event data in i.e. what arguments the method takes.
This way you can implement event triggering by
for (HandlerDescriptor desc : subscriptionMap.get(event)) {
desc.trigger(event);
}
, which should be plenty fast. You can have different HandlerDescriptors for handlers that take event info, ...
You can also make subscribe
itself faster, by caching the java.lang.reflect.Method
s at a class level (by a handler id key). Such that reflection is only used, when subscribe
ing a method of a class, not seen before.
What I'm not discussing here (hint: it's API style)
- How to name the annotations
- How to get context / event data in, you could take a look at JAX-RS for this.
Basically you'll also parse that info at setup time, e.g. by looking at the argument types, so that you don't need to dispatch for this at
.trigger()
time. - Whether to have subscribe / unsubscribe or return an Unsubscriber from subscribe. That's the age old event system api style question.
精彩评论