2

私は得る

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; import 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 は新しいオブジェクトへの参照を出力すべきではありませんか? 代わりに例外が発生する理由は何ですか?

4

3 に答える 3

2

Integer には、引数のないコンストラクターがありません。Integer(int)たとえば、代わりに を使用できます。

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

メソッドを呼び出すつもりならfoo、以下を使用できます。

Object obj = method.invoke(null); //null for static
于 2013-08-01T20:18:51.913 に答える
2

メソッドの戻り値の型はInteger、コンストラクターを持たないno-argです。foo メソッドでインスタンスを複製するには、次のようにします。

Object obj = method.getReturnType().getConstructor(int.class).newInstance(1);
于 2013-08-01T20:17:13.300 に答える
1

getReturnType()実行時に、メソッド

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

インスタンスを返しClass<Integer>ます。Integerクラスには 2 つのコンストラクターがあり、1 つは を使用し、intもう 1 つは を使用しStringます。

を呼び出すと、返されたクラス オブジェクトnewInstance()の既定のコンストラクターが期待no-argされますが、これは存在しません。

コンストラクタを取得する必要があります

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

次に、最も一致するものを繰り返して使用します。

于 2013-08-01T20:17:44.003 に答える