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