0

I have an ArrayList<Container>, However, Container can be Container<String>, Container<Integer> etc. while iterating the arraylist, I need to find out what type of container it is and respond accordingly. I know that java has type erasure, but is there a way to pre-store the type and retrieve it later? something like

public T type;

and to use it later such as

container.type A = container.dosomething();
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
Bonk
  • 1,859
  • 9
  • 28
  • 46

2 Answers2

0

At runtime Java does not keep type information on generics. Type deletion occurs and all containers are considered to be of the same runtime type. Using reflection it is possible to get information on generics, but it is rarely worth the effort. You should rather think about a redesign of your code, or using getClass() on an element in the container to determine the type of the actual elements in the container.

RudolphEst
  • 1,240
  • 13
  • 21
  • Creating your own container type which keeps a copy of the class is an example of a redesign that you might consider. – RudolphEst Mar 05 '13 at 14:30
0

The type of a variable is a compile-time concept. Its purpose is just for allowing the compiler to determine what operations are allowed with that variable or expression.

Therefore, a "type which is not known at compile time" is completely useless, because the compiler doesn't know anything about what can be done with it. So the variable might as well be typed Object.

newacct
  • 119,665
  • 29
  • 163
  • 224