开发者

Retrieving the type of a Collection

开发者 https://www.devze.com 2022-12-24 02:40 出处:网络
So I have something like the following in Java: private List<SomeType>variable; // ....variable is instantiated as so ...

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 = Surrou开发者_StackOverflow社区ndingClass.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 */


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.


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; }
0

精彩评论

暂无评论...
验证码 换一张
取 消