How can I achieve this?
public class GenericClass<T>
{
public Type getMyType()
{
//How do I return the type of T?
}
}
Everything I have tried so far always returns type Object
rather than the specific type used.
How can I achieve this?
public class GenericClass<T>
{
public Type getMyType()
{
//How do I return the type of T?
}
}
Everything I have tried so far always returns type Object
rather than the specific type used.
As others mentioned, it's only possible via reflection in certain circumstances.
If you really need the type, this is the usual (type-safe) workaround pattern:
Here is my solution
No matter how many level does your class hierarchy has, this solution still works, for example:
In this case, getMyType() = java.lang.String
Technique described in this article by Ian Robertson works for me.
In short quick and dirty example:
Here is my trick:
I dont think you can, Java uses type erasure when compiling so your code is compatible with applications and libraries that were created pre-generics.
From the Oracle Docs:
http://docs.oracle.com/javase/tutorial/java/generics/erasure.html