java - 调用 method.getReturnType().newInstance()(静态内部类的静态方法)时出现 InstantiationException

标签 java object static-methods inner-classes

我明白

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/

相关文章:

c# - 我应该为 DataAccess 常用运算符使用静态方法吗?

java - GreenMail 不返回密件抄送收件人地址

java - RestTemplate 映射到对象

javascript - Angular : What is the best way for storing objects in service for showing in view and crud functions to server

c# - 我应该为此创建一个单独的类吗?

c++ - "Named Constructor Idiom"似乎与静态方法不能访问非静态成员函数的规则相矛盾。有什么解释吗?

java - 迭代时修改集合中元素的概念?

java - 从内存编译 java 类失败,并且在 cmd 和 netbean ide 中输出两个不同的错误

c++ - 添加方法到库

javascript - 如何访问数组中对象中的数组?