首页 > 解决方案 > java反射constructor.newInstance给出“错误数量的参数”

问题描述

如何在下面修复我的代码?

package mypackage;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

public class testReflection {
    public class You {
        public You(String s) {
        }

        public void f(String s, int i) {
            System.out.println(i + 100);
        }
    }

    public static void main(String[] args) throws NoSuchMethodException {
        Constructor constructor =
                You.class.getConstructor(testReflection.class, String.class);
        try {
            You y = (You)constructor.newInstance("xzy");//Exception!!!!
            System.out.println("ok");
            y.f("xyz",2);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

异常消息是:

java.lang.IllegalArgumentException: wrong number of arguments
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at mypackage.testReflection.main

标签: javareflectionconstructor

解决方案


从以下文档Constructor#newInstance

如果构造函数的声明类是非静态上下文中的内部类,则构造函数的第一个参数需要是封闭实例;请参阅 Java™ 语言规范的第 15.9.3 节。

因为You是一个内部类,你需要一个它的封闭类testReflection的实例,来创建一个You. 为此,您可以使用以下内容:

You y = (You) constructor.newInstance(new testReflection(), "xzy");

我还建议将您的类名更改TestReflection为遵循正确的命名约定。


推荐阅读