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
An anonymous class of the form new -interface- implicitly extends Object. You have to use one of the constructors for Object. There is only one - the no-args constructor.
Make mylookupThread
separate class, make it's instance and pass it to 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));
Other way around is to 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);
This is the problem line (as you said:)
Runnable mylookupThread = new Runnable(FilePath, SearchIndex) { ...
What's happening is that we're defining a class on-the-fly, and that class implements the Runnable
interface. When you use this syntax, the items in the parentheses are intended as constructor arguments for the superclass. Since Runnable
is an interface, not a class, it has no constructors at all, so there are definitely none that take arguments.
That said, whatever those are supposed to be, they're not used in the body of the anonymous class, so to a first approximation, you want to just drop what's inside the parentheses altogether.
@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.