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. 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 testClassObject = new TestClass();
Maybe you're using different imports (eg a different Map than java.util.Map
)?
Everything works just as expected and prints "simpleMethod invoked".
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
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. "wrong number of arguments".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.