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.
I think there is another elegant solution.
What you want to do is (safely) "pass" the type of the generic type parameter up from the concerete class to the superclass.
If you allow yourself to think of the class type as "metadata" on the class, that suggests the Java method for encoding metadata in at runtime: annotations.
First define a custom annotation along these lines:
You can then have to add the annotation to your subclass.
Then you can use this code to get the class type in your base class:
Some limitations of this approach are:
PassedGenericType
) in TWO places rather than one which is non-DRY.This is my solution:
One simple solution for this cab be like below
Here is working solution!!!
NOTES: Can be used only as superclass
1. Has to be extended with typed class (
Child extends Generic<Integer>
)OR
2. Has to be created as anonymous implementation (
new Generic<Integer>() {};
)I used follow approach:
Here's one way, which I've had to use once or twice:
Along with