如何从object.getClass()返回的List <t>中获取typeArguments.getDeclaredField(“fieldname”)。getGenericType(); </t>

时间:2015-01-16 17:17:31

标签: java java-ee generics reflection

我正在解决这个问题大约2天,我仍然无法解决它。 我有这个方法:

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()"

    ....
    }

我可以获得班级类别吗?

1 个答案:

答案 0 :(得分:1)

您应该只能投放到ParameterizedType

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