java - How do I make an annotation based event system? -
well made 1 don't know if it's best tbh. can write me tutorial? made 1 tutorial , understood 90% of 10% of off , seems aint best way it.
eventmanager.java
public class eventmanager {
private static list<listener> registered = new arraylist<listener>(); public static void register(listener listener) { if (!registered.contains(listener)) { registered.add(listener); } } public static void unregister(listener listener) { if (registered.contains(listener)) { registered.remove(listener); } } public static list<listener> getregistered() { return registered; } public static void callevent(final event event) { new thread() { @override public void run() { call(event); } }.start(); } private static void call(final event event) { (listener registered : getregistered()) { method[] methods = registered.getclass().getmethods(); (int = 0; < methods.length; i++) { eventhandler eventhandler = methods[i].getannotation(eventhandler.class); if (eventhandler != null) { class<?>[] methodparams = methods[i].getparametertypes(); if (methodparams.length < 1) { continue; } if (!event.getclass().getsimplename().equals(methodparams[0].getsimplename())) { continue; } try { methods[i].invoke(registered.getclass().newinstance(), event); } catch (exception exception) { system.err.println(exception); } } } } }
}
eventhandler.java
@retention(retentionpolicy.runtime) @target(elementtype.method) public @interface eventhandler { }
and event.java , listener.java blank interfaces.
Comments
Post a Comment