views:

74

answers:

4

Hello,
In a java serialization problem, I want to save some classes name and I have some problems with generic classes. For example :
- If I have ArrayList<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 java.util.ArrayList<String> or ArrayList<String>

Any ideas on how I can do this?
Damien.

A: 

Switch to a language that supports it.

The behavior you describe is called type erasure and this is how generics are implemented in Java.

Alexander Pogrebnyak
+5  A: 
  1. The case you've described can't work, you probably do listToDump.getClass().getName()

  2. 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.

  3. 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.

Roman
(answer to point 3) : A program which uses my 'dump' cry and bug when it find a not generic Collection. So I wanted to do a workaround on my side, but seeing your answers I will tell the bugged program's programmer to see what happened in his side 'cause it's not normal :)
Damien
+2  A: 

It's not possible due to type erasure.

JRL
+3  A: 

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?

Michael Borgwardt