Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Instance by java.lang.reflect.Type

I want to set property of class by using reflect, and my class has a List<Article> property.

I just get the generics type of the List<Article> by below code

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


like image 250
Joe Avatar asked Nov 01 '22 14:11

Joe


1 Answers

(Answered in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )

The OP wrote:

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;
    }
}
like image 197
2 revs Avatar answered Nov 09 '22 11:11

2 revs