java反射 泛型类型,在运行时指定泛型集合类型参数(Java反射)

I'd like to get the generic type of a collection, using reflection, at runtime.

Code (JAVA):

Field collectionObject = object.getClass().getDeclaredField(

collectionField.getName());

//here I compare to see if a collection

if (Collection.class.isAssignableFrom(collectionObject.getType())) {

// here I have to use the generic type of the collection

// to see if it's from a specific type - in this case Persistable

if (Persistable.class.isAssignableFrom(GENERIC_TYPE_COLLECTION.class)) {

}

}

Is there a way of getting the generic type of the collection in java at runtime? In my case I need the .class of the collection's generic type.

Thanks in advance!

解决方案

Type erasure means that information about the generic type of an object simply isn't present at execution time.

(The link is to the relevant section of Angelika Langer's Java Generics FAQ which should answer virtually every question you could possibly ask about Java generics :)

However, you're not really interested in the type of an object - you're interested in the type of a field. I misread the question, and although the answer has been accepted I hope to make amends by fixing it now :)

If the field doesn't use a type parameter itself, it can be done. For example:

import java.lang.reflect.*;

import java.util.*;

public class Test

{

public List names;

public static void main(String [] args)

throws Exception // Just for simplicity!

{

Field field = Test.class.getDeclaredField("names");

ParameterizedType type = (ParameterizedType) field.getGenericType();

// List

System.out.println(type.getRawType());

// Just String in this case

for (Type typeArgument : type.getActualTypeArguments())

{

System.out.println(" " + typeArgument);

}

}

}

If the field were in a class T with the field being List then you'd have to know the type argument for the instance in order to know the type argument for the collection.

Translating this into your required code is somewhat tricky though - you really need to know the type argument at the point of the collection class. For instance, if someone declared:

public class StringCollection implements Collection

and then had a field of type StringCollection, that field itself wouldn't have any type arguments. You'd then need to check getGenericSuperType and getGenericInterfaces recursively until you found what you wanted.

It's really not going to be easy to do that, even though it's possible. If I were you I'd try to change your design so that you don't need this.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值