[英]How do I get typeArguments from a List<T> returned by object.getClass().getDeclaredField(“fieldname”).getGenericType();
我正在处理此问题大约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()"
....
}
我可以上课类别吗?
您应该可以将其转换为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.