1

Possible Duplicate:
How do I find out what type each object is in a ArrayList<Object>?
Knowing type of generic in Java

How can I retrieve the Type Foo from my ArrayList using the reflection in Java?

ArrayList<Foo> myList = new ArrayList<Foo>();
Community
  • 1
  • 1
Luca
  • 43
  • 2
  • 10
  • 4
    Type erasure --> can't get generic type at runtime! – jlordo Nov 19 '12 at 15:44
  • 1
    Well you can't using reflection BUT, let's think outside the box for a while, what's the class of the first element of your ArrayList<>()?? ^^ – Bruno Vieira Nov 19 '12 at 15:46
  • 1
    @jlordo Unless it's a [`Field`](http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Field.html#getGenericType()) – Tim Pote Nov 19 '12 at 15:46
  • see this: http://stackoverflow.com/questions/1886677/knowing-type-of-generic-in-java/1886728#1886728 – kosa Nov 19 '12 at 15:47
  • 2
    @BrunoVieira no, that is bad thinking! The first (or any other) element might be a descendant of the class `Foo`!!! – ppeterka Nov 19 '12 at 15:51
  • Or, the list might be empty. That kind of approach is dangerous and fragile. Find a better way to avoid reflection entirely. – Louis Wasserman Nov 19 '12 at 16:10
  • I need to use reflection because I need to implement `Parcelable` interface in some objects with about 100 fields each. Do you know a quicker and more flexible way than reflection? @LouisWasserman – Luca Nov 19 '12 at 16:26

1 Answers1

9

You can't get this type from the value, but you can get it from the Field information.

public class Main {
    interface Foo { }
    class A {
        List<Foo> myList = new ArrayList<Foo>();
    }
    public static void main(String... args) throws NoSuchFieldException {
        ParameterizedType myListType = ((ParameterizedType) 
                                A.class.getDeclaredField("myList").getGenericType());
        System.out.println(myListType.getActualTypeArguments()[0]);
    }
}

prints

interface Main$Foo

Fields, method arguments, return types and extended classes/interfaces can be inspected, but not local variables or values

These produce the same result.

List<Foo> myList = new ArrayList();
List<Foo> myList = (List) new ArrayList<String>();

You cannot obtain a generic type for

List myList = new ArrayList<Foo>();
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130