简体   繁体   English

以接口为参数调用私有方法

[英]Invoke private method with interface as argument

I've been attempting to invoke a private method whose argument is a parameter and I can't quite seem to get it right. 我一直在尝试调用一个参数为参数的私有方法,但似乎不太正确。

Here's kind of how the code looks so far: 到目前为止,代码看起来是这样的:

public class TestClass {
   public TestClass(){
   }

   private void simpleMethod( Map<String, Integer> testMap) {
      //code logic
   }
}

Then I attempt to use this to invoke the private method: 然后,我尝试使用它来调用私有方法:

//instance I would like to invoke simpleMethod on
TestClass testClassObject = new TestClass();

//Hashmap
Map <String, Integer> testMap = new HashMap <String, Integer>();

//method I want to invoke
Method simpleMethod = TestClass.class.getDeclaredMethod("simpleMethod", Map.class);
simpleMethod.setAccessible(true);

simpleMethod.invoke(testClassObject, testMap); //Throws an IllegalArgumentException 

As you can see, it throws an IllegalArgumentException. 如您所见,它将引发IllegalArgumentException。 I've attempted to cast the hashmap back to a map, but that didn't work. 我试图将哈希图重新投射回地图,但这没有用。

What am I doing wrong? 我究竟做错了什么?

I just tested it, and your code works 100% fine here, when I instantiate your TestClass object like: 我刚刚对其进行了测试,当我实例化您的TestClass对象时,您的代码在这里可以100%正常工作:

TestClass testClassObject = new TestClass();

Maybe you're using different imports (eg a different Map than java.util.Map )? 也许您使用的是不同的导入(例如,与java.util.Map不同的Map)?

Everything works just as expected and prints "simpleMethod invoked". 一切都按预期工作,并显示“ simpleMethod invoked”。

TestClass.java TestClass.java

import java.util.Map;

public class TestClass {
    public TestClass() {
    }
    private void simpleMethod(Map<String, Integer> testMap) {
        System.err.println("simpleMethod invoked");
    }
}

Caller.java Caller.java

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class Caller {
    public static void main(String[] args) throws IllegalArgumentException,
            IllegalAccessException, InvocationTargetException,
            SecurityException, NoSuchMethodException {
        // Hashmap
        Map<String, Integer> testMap = new HashMap<String, Integer>();

        // method I want to invoke
        Method simpleMethod = TestClass.class.getDeclaredMethod("simpleMethod",
                Map.class);
        simpleMethod.setAccessible(true);

        TestClass testClassObject = new TestClass();
        simpleMethod.invoke(testClassObject, testMap);
    }
}

The code as posted works fine for me. 发布的代码对我来说很好。 Tweaking the code a little, I get an IllegalArgumentException when testMap is null. 稍微调整一下代码,当testMap为null时,我得到一个IllegalArgumentException。 "wrong number of arguments". “参数数量错误”。

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

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