Tom Tom - 3 months ago 18
Java Question

Java - Pass a method to a class and execute it in a new Thread

As in the title, I'd like to write a class which takes in a method and executes it in a new Thread. I lurked around SO and came up with something like:

import java.util.concurrent.Callable;

public class MyExecutor<T> implements Runnable{

private Callable<T> method;


public <T> MyExecutor(Callable<T> pMethod){
this.method = pMethod;
}

@Override
public void run() {
try {
// start a new Thread, then
method.call();
} catch (Exception e) {
System.err.println("Failed calling method "+method.getClass());
e.printStackTrace();
}

}

}


However Eclipse warns me that, inside the constructor, in

this.method = pMethod;


I
cannot convert from Callable <T> to Callable <T>
.

It smells like I'm doing something entirely wrong, but I can't grasp it.

Answer

Since you added a type parameter <T> to your constructor, it shadows the type parameter for the class. Therefore, the T for the constructor argument pMethod is a different T than the class parameter, which is what Eclipse is warning you about. Just change the signature for the constructor to public MyExecutor(...).