获取 typeArguments-6ren"> 获取 typeArguments-我已经解决这个问题大约2天了,但仍然无法解决。我有这个方法: public List findByKeyValue(String key, String value, Object t) { -6ren">
gpt4 book ai didi

java - 如何从 object.getClass().getDeclaredField ("fieldname").getGenericType(); 返回的 List 获取 typeArguments

转载 作者:行者123 更新时间:2023-12-01 12:00:48 24 4
gpt4 key购买 nike

我已经解决这个问题大约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) {
...
}
}

关于java - 如何从 object.getClass().getDeclaredField ("fieldname").getGenericType(); 返回的 List<T> 获取 typeArguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27989292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com