This seems to be valid Java syntax:
<T> T get();
But what does it mean? And is it useful?
CLARIFICATION FOR DOWNVOTERS
I understand what it means when the T
is used in the method parameters, like this:
T get(Class<T> clazz);
The return type is inferrable from the class that's passed in.
But when you have no parameters to say what type T is, what type is it?
It is the type of the variable you are assigning the return-value to.
e.g. If you have a method like this one:
public static <T> T getGenericNumber() {
// the number-generator might return int, double, float etc. values
return (T) numberGenerator.getANumber();
}
You can for instance assign the return value of the method directly to a double value - without a cast:
Double a = getGenericNumber();
So you have basically moved your cast from the declaration of the variable into the method.
This is potentially dangerous because you can easily produce cast-exceptions cause you could do things like this - and still being able to compile:
String s = getGenericNumber();
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