I couldn’t find a duplicate for this question for Java, although there are a lot of them for C#.
I have this method:
public <T> T getSomething() {
//
}
According to the type of T, I will have a different return. For example:
String a = getSomething();
int b = getSomething();
For a, my method will return a specific String. For b, it will return a specific int. And so on.
It seems that this can be done with typeof() in C#. How can I achieve it in Java?
Unfortunately this is not possible with Java because it uses a technique called “type erasure” to allow generics to work without changing the JVM. The upshot is that when the method is called, all it knows about are Objects, so it can’t ever find out what type it is expected to return.