我明白了
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)
当我运行这个时: package newinstancetest; 导入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 不应该打印对新对象的引用吗?知道为什么我会得到异常吗?