gpt4 book ai didi

java - 如何通过 java.lang.reflect.Type 创建实例

转载 作者:搜寻专家 更新时间:2023-10-31 20:28:51 25 4
gpt4 key购买 nike

我想使用反射设置类的属性,我的类有一个 List<Article>属性(property)。

我刚得到 List<Article> 的泛型类型通过下面的代码

Method[] methods = target.getClass().getMethods();
String key = k.toString(), methodName = "set" + key;
Method method = getMethod(methods, methodName);
if (Iterable.class.isAssignableFrom(method.getParameterTypes()[0])) {
// at there, i get the generics type of list
// how can i create a instance of this type?
Type type = getGenericsType(method);
}


public static Method getMethod(Method[] methods, String methodName) {
for (Method method : methods) {
if (method.getName().equalsIgnoreCase(methodName))
return method;
}
return null;
}

private static Type getGenericsType(Method method) {
Type[] types = method.getGenericParameterTypes();
for (int i = 0; i < types.length; i++) {
ParameterizedType pt = (ParameterizedType) types[i];
if (pt.getActualTypeArguments().length > 0)
return pt.getActualTypeArguments()[0];
}
return null;
}


最佳答案

(在问题编辑中回答。转换为社区维基答案。参见 Question with no answers, but issue solved in the comments (or extended in chat))

OP 写道:

I just solved it with a stupid solution,

its instantiation generics type by using Class.forName();

the class name came from type.toString()

Type type = getGenericsType(method);
Class<?> genericsType = null;
try {
genericsType = Class.forName(getClassName(type));
// now, i have a instance of generics type
Object o = genericsType.newInstance();
} catch (Exception e) {

}

static String NAME_PREFIX = "class ";

private static String getClassName(Type type) {
String fullName = type.toString();
if (fullName.startsWith(NAME_PREFIX))
return fullName.substring(NAME_PREFIX.length());
return fullName;
}

by the way, there is the code of the class that has the List<Article>

public class NewsMsg {
private List<Article> articles;

public List<Article> getArticles() {
return articles;
}

public void setArticles(List<Article> articles) {
this.articles = articles;
}
}

关于java - 如何通过 java.lang.reflect.Type 创建实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18776749/

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