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

Joe*_*Joe 5 java reflection

我想通过使用reflect来设置类的属性,而我的类有一个List<Article>属性.

我只是得到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;
}
Run Code Online (Sandbox Code Playgroud)


Bri*_*汤莱恩 2

(在问题编辑中回答。转换为社区 wiki 答案。请参阅没有答案的问题,但问题已在评论中解决(或在聊天中扩展)

OP 写道:

我只是用一个愚蠢的解决方案解决了这个问题

它的实例化泛型类型通过使用Class.forName();

类名来自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;
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,有一个类的代码List<Article>

public class NewsMsg {
    private List<Article> articles;

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

    public void setArticles(List<Article> articles) {
        this.articles = articles;
    }
}
Run Code Online (Sandbox Code Playgroud)