自定义EventListener检查类重写了哪种抽象方法

时间:2019-03-10 12:25:19

标签: java events listener

你好,我得到了以下代码:

事件处理程序.java

package me.xenopyax.edla.watcher;

import static java.nio.file.StandardWatchEventKinds.*;

import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.util.ArrayList;
import java.util.List;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

public class EventHandler {

private Path folderPath = Paths.get(System.getProperty("user.dir") + "/Saved Games/Frontier Developments/Elite Dangerous");
private String watchFile;
private List<EventListener> listeners = new ArrayList<>();

  public EventHandler()  {

    // We obtain the file system of the Path
    FileSystem fileSystem = folderPath.getFileSystem();

    // We create the new WatchService using the try-with-resources block
    try (WatchService service = fileSystem.newWatchService()) {
        // We watch for modification events
        folderPath.register(service, ENTRY_MODIFY);

        // Start the infinite polling loop
        while (true) {
            // Wait for the next event
            WatchKey watchKey = service.take();

            for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
                // Get the type of the event
                Kind<?> kind = watchEvent.kind();

                if (kind == ENTRY_MODIFY) {
                    Path watchEventPath = (Path) watchEvent.context();

                    // Call this if the right file is involved
                    if (watchEventPath.toString().equals(watchFile)) {
                        //File has been modified, call event registered

                    }
                }
            }

            if (!watchKey.reset()) {
                // Exit if no longer valid
                break;
            }

        }

    } catch (IOException | InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
  }

  public void registerListener(EventListener listener) {
      listeners.add(listener);
  }

}

Main.java

package me.xenopyax.edla;

import java.io.File;

import me.xenopyax.edla.discord.EDLARPC;
import me.xenopyax.edla.watcher.EventHandler;
import me.xenopyax.edla.watcher.GameStartListener;

public class Main {

  private EDLARPC edlarpc = new EDLARPC();
  private File journalDir = new File(System.getProperty("user.home") + "/Saved Games/Frontier Developments/Elite Dangerous");

  public static void main(String[] args) {

    EventHandler handler = new EventHandler();

    handler.registerListener(new GameStartListener());

  }

  public EDLARPC getRPC() {
    return edlarpc;
  }

  public File getJournalDirectory() {
    return journalDir;
  }

EventListener.java

package me.xenopyax.edla.watcher;

public abstract class EventListener {

    public void onGameStart(){};


}

和GameStartListener.java

package me.xenopyax.edla.watcher;

public class GameStartListener extends EventListener {

  @Override
  public void onGameStart() {



  }

}

现在我的问题是如何从 EventHandler.java 中的 EventListener.java 调用抽象方法,以及如何检入 ArrayList 哪些方法被覆盖?我试图创建一个侦听文件的EventHandler,当发生更改时,它查找更改的内容并从 EventListener.java 中触发适当的抽象方法。

1 个答案:

答案 0 :(得分:0)

如果不是抽象类,则可以检查方法的声明类,则该方法被覆盖。

import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

class Main {
    static abstract class EventListener {
        public void onFileChanged() {
            throw new NotImplementedException();
        }
    }

    static class EventListenerNotImpl extends EventListener {

    }

    static class EventListenerImpl extends EventListener {
        private String id;

        public EventListenerImpl(String id) {
            this.id = id;
        }

        public void onFileChanged() {
            System.out.println(id + ":" + EventListenerImpl.class.getCanonicalName() + ".onFileChanged() was called");
        }
    }

    static class EventHandler {
        private List<EventListener> listeners = new ArrayList<>();

        public void addListener(EventListener listener) {
            listeners.add(listener);
        }

        private void propagateOnFileChangedEvent() {
            listeners.forEach(l -> {
                try {
                    Method m = l.getClass().getMethod("onFileChanged");
                    if (!m.getDeclaringClass().equals(EventListener.class)) {
                        l.onFileChanged();
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    public static void main(String[] args) {
        EventHandler handler = new EventHandler();

        handler.addListener(new EventListenerImpl("listener-1"));
        handler.addListener(new EventListenerNotImpl()); // Not will be invoked onFileChangedEvent
        handler.addListener(new EventListenerImpl("listener-3"));

        handler.propagateOnFileChangedEvent();
    }
}

输出:

listener-1:Main.EventListenerImpl.onFileChanged() was called
listener-3:Main.EventListenerImpl.onFileChanged() was called