我已经做了一个,但我不知道它是否是最好的。谁能给我写一个好的教程?我用一个教程制作了这个,我理解了它的90%但是10%的关闭,这似乎是最好的方法。
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) {
for (Listener registered : getRegistered()) {
Method[] methods = registered.getClass().getMethods();
for (int i = 0; i < 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 {
}
和Event.java和Listener.java是空白接口。