我明白
run: method: foo
Return type: class java.lang.Integer
Exception in thread "main" java.lang.InstantiationException: java.lang.Integer
at java.lang.Class.newInstance0(Class.java:359)
at java.lang.Class.newInstance(Class.java:327)
at newinstancetest.NewInstanceTest.main(NewInstanceTest.java:10)
Java Result: 1 BUILD SUCCESSFUL (total time: 0 seconds)
当我运行这个时: 打包新实例测试; 导入java.lang.reflect.Method;
public class NewInstanceTest {
public static void main(String[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException {
Method method = InnerClass.class.getDeclaredMethod("foo", null);
System.out.println("method: " + method.getName());
System.out.println("Return type: " + method.getReturnType());
Object obj = method.getReturnType().newInstance();
System.out.println("obj: " + obj);
}
public static class InnerClass {
public static Integer foo() {
return new Integer(1);
}
}
}
“obj”+ obj 不应该打印对新对象的引用吗?知道为什么我会得到异常吗?
最佳答案
该方法的返回类型是Integer
,它没有no-arg
构造函数。要复制 foo 方法中的实例,您可以这样做
Object obj = method.getReturnType().getConstructor(int.class).newInstance(1);
关于java - 调用 method.getReturnType().newInstance()(静态内部类的静态方法)时出现 InstantiationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18003616/