Tom Tom - 2 months ago 4x
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;

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



However Eclipse warns me that, inside the constructor, in

this.method = pMethod;

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

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


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(...).