Get a class name with generics information
In a java serialization problem, I want to save some classes name and I have some problems with generic classes. For example :
- If I haveArrayList<String> listToDump = new ArrayList<String>();
- If I take the name : listToDump.getName();
or listToDump.getCanonicalName();
- I will have java.util.ArrayList
or ArrayList
- And I want to have jav开发者_运维问答a.util.ArrayList<String>
or ArrayList<String>
Any ideas on how I can do this?
Damien.The case you've described can't work, you probably do
listToDump.getClass().getName()
There is no way to get information about generic type in runtime due to type erasure:
When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method.
If you describe in detail what problem you're trying to solve then maybe we'll suggest you some workarounds or even solutions. Type erasure shouldn't be a big issue, it just can change the way of doing some things.
If listToDump
is a field, you could use Field.getGenericType(). But Java generics are erased at runtime - there is just a plain ArrayList
instance. You could look at its contents and find the common supertype, but that gets very tricky when interfaces are involved, and could be more specific than you want.
But how are you actually planning to use the information?
It's not possible due to type erasure.
I think if you extract any element from the List
then try fetch its class name you would get the result you seek.
Switch to a language that supports it.
The behavior you describe is called type erasure and this is how generics are implemented in Java.
精彩评论