匿名类如何有参数?

我不是一个java人,但我inheritance了一些我需要补丁的代码。 我将源代码转换为netbeans,我收到错误:匿名类实现接口; 不能有参数。

这是代码:

Executor background = Executors.newSingleThreadExecutor(); Runnable mylookupThread = new Runnable(FilePath, SearchIndex) { public void run() { MainWindow.this.processFile(this.val$FilePath); Thread t = new Thread(new lookupThread(MainWindow.arrFile, true, false, this.val$SearchIndex)); t.setName("Lookup"); t.setPriority(10); t.start(); } }; background.execute(mylookupThread); Executor statusThread = Executors.newSingleThreadExecutor(); Runnable myStatusThread = new Runnable() { public void run() { MainWindow.this.updateStatus(); } }; statusThread.execute(myStatusThread); 

错误会在第二行弹出。 救命?!?

使mylookupThread单独的类,使其成为实例并将其传递给Executor

 class LookupTask implements Runnable { private final String filePath, searchIndex; LookupTask(String filePath, String searchIndex) { this.filePath = filePath; this.searchIndex = searchIndex; } public void run() { ... } } ... background.execute(new LookupTask(filePath, searchIndex)); 

另一种方法是make filePath, searchIndex final:

 final String filePath = ... final String searchIndex = ... Executor background = Executors.newSingleThreadExecutor(); 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(); } }; background.execute(mylookupThread); 

new -interfaceforms的匿名类隐式扩展了Object。 您必须使用Object的构造函数之一 。 只有一个 – 无参数构造函数。

@Victor是对的,你可以创建另一个类。 您还可以在匿名类中使用final变量。 像下面这样的东西会起作用。

 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(); } }; 

顺便说一句。 在执行程序中执行的线程的Runnable中创建一个线程有点奇怪。 不确定为什么你不会直接生成LookupThread并完全删除匿名类。

这是问题线(如你所说:)

 Runnable mylookupThread = new Runnable(FilePath, SearchIndex) { ... 

发生的事情是我们正在动态定义一个类,并且该类实现了Runnable接口。 使用此语法时,括号中的项目将用作超类的构造函数参数。 由于Runnable是一个接口,而不是一个类,它根本没有构造函数,因此肯定没有接受参数。

也就是说,无论那些应该是什么,它们都没有在匿名类的主体中使用,所以对于第一个近似,你想要完全放弃括号内的内容。