简体   繁体   English

如何从列表中获取typeArguments <T> 由object.getClass()。getDeclaredField(“ fieldname”)。getGenericType()返回;

[英]How do I get typeArguments from a List<T> returned by object.getClass().getDeclaredField(“fieldname”).getGenericType();

I am working on this problem for about 2 days and I still can not solve it. 我正在处理此问题大约2天,但仍然无法解决。 I have this the method: 我有这个方法:

public List<T> findByKeyValue(String key, String value, Object t) {
    Field field;
    Class<?> clazz = t.getClass();

    field = clazz.getDeclaredField(key);
    Type type = field.getType();

    if(type.equals(List.class)) {

        // HERE IS THE PROBLEM, the value of "field" is "public java.util.List com.cacobr.model.Video.categoryCollection" and categoryCollection is a List <Category>
        // **I need to get the class "Category" with Reflection**
        // The "field.getGenericType()" command returns "java.util.List <com.cacobr.model.Category>"
        // If I could use something like ".getActualTypeArguments()[0]" could return the class "Category" but I can't use this method after a "getGenericType()"

    ....
    }

Can I get the class Category? 我可以上课类别吗?

You should be able to just cast to ParameterizedType : 您应该可以将其转换为ParameterizedType

Type type = field.getGenericType();
if (type instanceof ParameterizedType) {
    ParamterizedType pt = (ParameterizedType) type;
    if (pt.getRawType() == List.class &&
        pt.getActualTypeArguments()[0] == Category.class) {
        ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM