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

时间:2013-09-13 01:18:49

标签: 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;
}


1 个答案:

答案 0 :(得分:2)

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

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