如何从 object.getClass().getDeclaredField("fieldname").getGenericType(); 返回的 List<T> 中获取 typeArguments
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()"
....
}
我可以得到 class 类别吗?
您应该可以转换为 ParameterizedType
:
Type type = field.getGenericType();
if (type instanceof ParameterizedType) {
ParamterizedType pt = (ParameterizedType) type;
if (pt.getRawType() == List.class &&
pt.getActualTypeArguments()[0] == Category.class) {
...
}
}
我已经为这个问题工作了大约 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()"
....
}
我可以得到 class 类别吗?
您应该可以转换为 ParameterizedType
:
Type type = field.getGenericType();
if (type instanceof ParameterizedType) {
ParamterizedType pt = (ParameterizedType) type;
if (pt.getRawType() == List.class &&
pt.getActualTypeArguments()[0] == Category.class) {
...
}
}