Reputation: 5709
I have a class
class ClassA<B extends ClassC>
{
................
}
In another class I have a list of objects of type A.
List<A<?>> cl = new ArrayList<A<?>>();
cl.add(new ClassB1(....));
where ClassB1 extends ClassC. How can I find out the type of objects in the list? i.e. The first object in the list is of type ClassB1.
Adding actual code
ClassA<ClassB1> af = new ClassA<ClassB1>();
List<ClassA<?>> afl = new ArrayList<ClassA<?>>();
afl.add(af);
for(ClassA<?> a: afl)
System.out.println(a.getClass());
This prints only ClassA and not ClassB1.
Upvotes: 0
Views: 142
Reputation: 597076
If you put objects of different classes, you can iterate the list and use getClass()
.
Update: this information is lost at runtime due to type erasure. So you can't get it.
Upvotes: 2
Reputation: 82559
You can get the class with getClass()
if you really, really, realllllyyy need to.
However, I would advise you to reconsider the notion of needing to get the class in the first place. If you're going to treat the classes differently, it probably isn't as generic as you think. Consider refactoring to a more appropriate approach.
Upvotes: 3