5

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


3
  • 3
    Get sure that the Type is an instance of Class (I doubt you can instantiate any other type) and use the instantiation methods from Class.
    – SJuan76
    Sep 13, 2013 at 1:23
  • Can you add the code of the class that has a List<Article> property? It will make it easier to test. Sep 13, 2013 at 1:28
  • 1
    Are you sure it's not a type erasure issue? Also it's not 100% clear what is the question exactly...
    – Eran Medan
    Sep 13, 2013 at 1:28

1 Answer 1

2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.