简体   繁体   中英

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. 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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