![](/img/trans.png)
[英]How To Instantiate a java.util.ArrayList with Generic Class Using Reflection
[英]Java Generic Method to Instantiate any Class with any Constructor using Reflection
众所周知,Java使用擦除,因此任何泛型类都无法做到
T t = new T();
因此,我尝试使用Java反射来创建一个带有Static方法的类,以实例化具有任何Constructor的任何Class。 这是代码。
import java.lang.reflect.*;
public class GenericNewInstance {
public static <T> T createInstance(Class<T> cObj) {
try {
return cObj.newInstance();
} catch (InstantiationException e) {
System.out.println("Instantiation Exception");
return null;
} catch (IllegalAccessException e) {
System.out.println("Illegal Access Exception");
return null;
}
}
public static <T> T createInstanceUsingRelection(Class<T> c, Object... initArgs) {
Constructor<T> cTor = null;
Class<?>[] cObjs = new Class<?>[initArgs.length];
int i = 0;
for(Object o : initArgs) {
cObjs[i++] = o.getClass();
}
try {
cTor = c.getConstructor(cObjs);
} catch (SecurityException e) {
System.out.println("security exception. Cannot get Constructor");
return null;
} catch (NoSuchMethodException e) {
System.out.println("NoSuchMethodException Cannot get constructor");
return null;
}
try {
return cTor.newInstance(initArgs);
} catch (IllegalArgumentException e) {
System.out.println("Illegal Argument Exception");
return null;
} catch (InstantiationException e) {
System.out.println("Instantiation Exception");
return null;
} catch (IllegalAccessException e) {
System.out.println("Illegal Access Exception");
return null;
} catch (InvocationTargetException e) {
System.out.println("Invocation Target Exception");
return null;
}
}
}
使用此示例。
Integer i = GenericNewInstance.createInstanceUsingRelection(Integer.class, "0");
所以我的问题是:
您的代码将在c.getConstructor(cObjs)
处失败,因为这没有考虑类型层次结构。 如果任何参数是构造函数的声明的param类型的子类型,则此调用不会返回它。 您需要更多类型的杂耍才能使其正常工作。 我建议您看一下已经解决了这个问题的代码 。 也许您甚至可以选择使用该库。 这是Clojure的实现代码,Clojure是一种基于JVM的动态语言,正好需要这些东西。 该库可从Maven中央存储库中获得。
顺便说一句,您的异常处理是多余的。 只需声明throws Exception
或捕获任何Exception
并将其包装在RuntimeException
。 当某件事失败时,原始异常是最好的诊断方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.