【问题标题】:InstantiationException on call to method.getReturnType().newInstance(), a static method of a static inner class调用 method.getReturnType().newInstance() 时的 InstantiationException,静态内部类的静态方法
【发布时间】:2013-08-02 22:34:09
【问题描述】:

我明白了

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 不应该打印对新对象的引用吗?知道为什么我会得到异常吗?

【问题讨论】:

    标签: java object static-methods inner-classes


    【解决方案1】:

    该方法的返回类型是Integer,它没有no-arg 构造函数。要在 foo 方法中复制实例,您可以这样做

    Object obj = method.getReturnType().getConstructor(int.class).newInstance(1);
    

    【讨论】:

      【解决方案2】:

      在运行时,方法getReturnType()

      Object obj = method.getReturnType().newInstance();
      

      返回一个Class<Integer> 实例。 Integer 类有两个构造函数,一个是int,一个是String

      当您调用 newInstance() 时,您期望返回的类对象的默认 no-arg 构造函数不存在。

      你需要得到构造函数

      Constructor[] constructors = d.getReturnType().getConstructors();
      

      然后迭代并使用最匹配的那个。

      【讨论】:

        【解决方案3】:

        整数没有没有参数的构造函数。您可以改用Integer(int),例如:

        Object obj = method.getReturnType().getConstructor(int.class).newInstance(0);
        

        如果您打算调用foo 方法,那么您可以使用:

        Object obj = method.invoke(null); //null for static
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-01-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多