How can an anonymous class have arguments?

后端 未结 4 1620
庸人自扰
庸人自扰 2021-01-22 05:42

I\'m not a java guy but I\'ve inherited some code I need to patch up. I pulled the source into netbeans and I\'m getting the error: Anonymous class implements interface; cannot

4条回答
  •  一整个雨季
    2021-01-22 06:25

    @Victor is right that you can create another class. You can also use variables inside an anonymous class that are final. Something like the following will work.

    Executor background = Executors.newSingleThreadExecutor();
    private final FilePath filePath = ...;
    private final String searchIndex = ...;
    Runnable mylookupThread = new Runnable() {
        public void run() {
            MainWindow.this.processFile(filePath);
            Thread t = new Thread(new lookupThread(MainWindow.arrFile, true, false,
               searchIndex));
            t.setName("Lookup");
            t.setPriority(10);
            t.start();
        }
    };
    

    Btw. It's a little strange to create a thread inside the Runnable of a thread executing in an executor. Not sure why you wouldn't just spawn the LookupThread directly and remove the anonymous class altogether.

提交回复
热议问题