Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I restrict Java Generics

Tags:

java

generics

I have the following code:

protected <T> T getValueForKey(String key) {

    T value = null;

    // currentStats is just a Bundle
    if (currentStats.containsKey(key)) {
        return value;
    }
    return value;
}

How can I set restrictions? I.e. the T to be String or int or double for example. Is this possible?

P.S.

I don't want to use

protected <T extends String> T getValueForKey(String key) {

}

Because I don't want to have only Strings..

like image 598
Alex Dowining Avatar asked Jan 07 '13 17:01

Alex Dowining


2 Answers

Since you can't overload the return value I would suggest to have different accessor methods:

protected int     getIntForKey(String key);
protected double  getDoubleForKey(String key);
protected String  getStringForKey(String key);
like image 98
stacker Avatar answered Sep 29 '22 23:09

stacker


I dont think there is a way to restrict a generic type to only String, Integer and Double, but you could use <T extends Comparable> As String, Integer and Double all implement Comparable. But many other class's also implement Comparable like java.util.Date,

like image 33
PermGenError Avatar answered Sep 29 '22 23:09

PermGenError