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..
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);
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With