How to create Instance by java.lang.reflect.Type
I want to set property of class by using reflect,
and my class have a List<Article> property.
i just get the generics type of the List<Artile> 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;
}
EDIT:
i just solved it with a stupid solution,
its instantiation generics type by using Class.forName();
the class name come 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;
}
No comments:
Post a Comment