5

我想通过使用反射设置类的属性,我的类有一个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;
}


4

1 回答 1

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;
}

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

public class NewsMsg {
    private List<Article> articles;

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

    public void setArticles(List<Article> articles) {
        this.articles = articles;
    }
}
于 2015-01-31T11:07:07.263 回答