views:

55

answers:

2

So I have something like the following in Java:

private List<SomeType>variable;

// ....variable is instantiated as so ...
variable = new ArrayList<SomeType>();

// there's also a getter
public List<SomeType> getVariable() { /* code */ }

What I would like to be able to do is figure out that variable is a collection of SomeType programmatically. I read here that I can determine that from the method getVariable() but is there any way to tell directly from variable?

I have been able to retrieve SomeType from the getter method based on the information in the link. I have also been successful in retrieving all the fields of the surrounding class via SurroundingClass.getClass().getDeclaredFields() but this doesn't tell me that it is List<SomeType>.

EDIT: Based on bmargulies's response doing the following will achieve what I want:

Field[] fields = SurroundingClass.getDeclaredFields();
/* assuming it is in fields[0] and is a ParameterizedType */
ParameterizedType pt = (ParameterizedType) fields[0].getGenericType(); 
Type[] types = pt.getActualTypeArguments();
/* from types I'm able to see the information I've been looking for */
+6  A: 

You can't get this from the instance, due to type erasure. At runtime, XXX<T> is really just XXX. Unless the class makes special arrangements to store a Class reference for the T, it's completely and totally gone.

You can get it from getDeclaredFields(). You have to call getGenericType on the Field, not getType, and then you have to do some casting to ParameterizedType and then ask it for the parameter you want.

bmargulies
Ahh, getDeclaredFields() turns out to work perfectly after casting it to ParameterizedType.
nevets1219
+1  A: 

You can get SomeType by looking at one of the elements in the Collection

Collection<String> abc = new ArrayList<String>();
for ( Object x : abc ) { String className = x.getClass().getName(); break; }
David
I thought about trying this but didn't because I don't have an actual object to work with and I didn't want to instantiate an instance of this object either. However, good to know this is a valid approach as well.
nevets1219