简体   繁体   English

使用反射调用具有参数的Inner类方法

[英]Invoke Inner class method having parameters using reflection

I am trying to test my code though knowing using reflection is not a good way of testing. 我试图测试我的代码虽然知道使用反射不是一个好的测试方法。 I have a outer class as public having private inner class with a public method as below, 我有一个外部类作为公共私有内部类具有公共方法,如下所示,

public class Outer {

    private class Inner {
        private int var = 1;

        public Inner(int a) {
            System.out.println("___");
        }

        public void test(int a) {
            System.out.println("Hey");
        }
    }
}

My main java class looks like below 我的主要java类如下所示

main() {
    Outer b = new Outer();
    System.out.println(b);
    Class<?> innerClass = Class.forName("car.Outer$Inner");

    Constructor<?> constructor = innerClass.getDeclaredConstructor(Outer.class, 1);

    constructor.setAccessible(true);
    Object c = constructor.newInstance(b,b);

    Method method = c.getClass().getDeclaredMethod("test");
    method.setAccessible(true);
    method.invoke(c, 1);
}

This is throwing 这是投掷

Exception in thread "main" java.lang.NoSuchMethodException: car.Outer$Inner.test() at java.lang.Class.getDeclaredMethod(Class.java:2130) at car.A.main(A.java:36) 线程“main”中的异常java.lang.NoSuchMethodException:car.Auter $ Inner.test()at java.lang.Class.getDeclaredMethod(Class.java:2130)at car.A.main(A.java:36)

How to invoke inner class method taking parameter using reflection? 如何使用反射调用内部类方法?

You need to supply the argument class(es) in the call to getDeclaredMethod() . 您需要在调用getDeclaredMethod()提供参数类。 When you call getDeclaredMethod() , the first argument is the name of the method you want looked up and any remaining arguments are the classes of the argument(s) to the method you want. 当您调用getDeclaredMethod() ,第一个参数是您想要查找的方法的名称,任何剩余的参数是您想要的方法的参数的类。 This is how getDeclaredMethod() distinguishes between overloaded method names to get one particular method. 这就是getDeclaredMethod()区分重载方法名称以获取一个特定方法的方法。 Since you have supplied no additional arguments, getDeclaredMethod() is looking for a method named test that takes no arguments. 由于您没有提供其他参数,因此getDeclaredMethod()正在寻找一个名为test的方法,该方法不带参数。 You're getting an exception because you have no such method in class Outer$Inner . 你得到一个例外,因为你在类Outer$Inner没有这样的方法。 The only test method you do have takes an int parameter`, so the following should do what you want: 你唯一的test方法是一个int参数`,所以下面应该做你想要的:

Method method = c.getClass().getDeclaredMethod("test", int.class);

Here, int.class is the Class object corresponding to the primitive argument type int . 这里, int.class是对应于原始参数类型intClass对象。

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

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