简体   繁体   English

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

[英]InstantiationException on call to method.getReturnType().newInstance(), a static method of a static inner class

I get 我懂了

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)

When I run this: package newinstancetest; 当我运行此命令时:package newinstancetest; import java.lang.reflect.Method; 导入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);
    }
}
}

Shouldn't the "obj" + obj print the reference to a new object? “ obj” + obj是否应该打印对新对象的引用? Any idea why i get an exception instead? 知道为什么我会得到例外吗?

The return type for the method is Integer which does not have a no-arg constructor. 该方法的返回类型是Integer ,它没有no-arg构造函数。 To replicate the instance in the foo method, you could do 要在foo方法中复制实例,您可以执行

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

Integer does not have a contructor with no argument. 整数没有没有参数的构造函数。 You can use the Integer(int) instead for example: 您可以改用Integer(int)例如:

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

If you meant to call the foo method, then you can use: 如果您打算调用foo方法,则可以使用:

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

At runtime, the method getReturnType() in 在运行时,方法getReturnType()

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

returns a Class<Integer> instance. 返回Class<Integer>实例。 The Integer class has two constructors, one with int and one with String . Integer类具有两个构造函数,一个具有int ,另一个具有String

When you call newInstance() , you're expecting the default no-arg constructor of the returned class object, which doesn't exist. 当调用newInstance() ,您期望返回的类对象的默认no-arg构造函数不存在。

You need to get the constructors 您需要获取构造函数

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

then iterate and use the one that matches best. 然后迭代并使用最匹配的那个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM