Martin Pfeffer
Martin Pfeffer

Reputation: 12627

Generics in Java-Thread

I want to code a little library for myself. Here is some code which I want to provide in it.

public class ThreadUtils {    
    private static String result;   
    public static Void runInBackground(final Callable<Void> func) {    
        new Thread(new Runnable() {
            public void run() {
                try {
                    func.call();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();    
        return null;
    }  
    public static String runInBackground(final Callable<String> func) {    
        result = "";    
        new Thread(new Runnable() {
            public void run() {
                try {
                    result = func.call();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();    
        return result;
    }    
}

I'm quite surprised that my IDE says that it won't work, because of a duplicate declaration. Why is that, normally it recognizes that the parameter are different, but it won't? How can it be made that runInBackground is able to return different primitive types?

Upvotes: 0

Views: 1004

Answers (1)

Hoopje
Hoopje

Reputation: 12932

Because of type erasure, generics in Java are not available at run-time. This means that you have two methods with the same name and same argument types, therefore Java cannot choose which one to use.

You will have to give your methods different names:

public static Void calculateVoidInBackground(final Callable<Void> func) {
    ...
}    
public static String calculateStringInBackground(final Callable<String> func) {
    ...
}  

To answer your second question: primitive types cannot be used as generic parameters. You can however use the wrapper classes (such as Integer, Long, Double) provided by Java. Because of auto-boxing primitive types are automatically converted to instances of the wrapper classes and vice versa:

public static int calculateIntInBackground(final Callable<Integer> func) {
    ...
}  

Upvotes: 2

Related Questions