My question is, how to invoke a method using reflection, with giving invoker object and multiple parameters, without giving invoker object type and parameters type and without calling API.
That is
Student student = new Student();
student.setNameAndClass("John", "1D"); // Method 0
can be replaced by
MyMethodUtils.invoke(student, "setNameAndClass", Object[] {"John", "1D"}); // Method 1
where the invoke()
method is made by JDK methods. It can be in other signature if it fulfill the requirement.
My research and study
I cannot find any related solution in StackOverflow. This answer need class list This looks pretty close but it is C# and calling API
I am able to make the invoke()
method like this.
MyMethodUtils.invoke(student, "getNameAndClass"); // Method 2 (no parameters)
MyMethodUtils.invoke(student, "setNameAndClass", Object[] {"John", "1D"},
Class[] {String.class, String.class}); // Method 3 (with multiple parameters but inconvenient to use)
Method 2, 3 works properly. However, when I tried to implement the Method 1 (what I want), it is working only when the type is exact match.
For example, if the method is like
setMarks(String name, Collection<Integer> marks);
native invoking works but reflection don't
student.setMarks("John", new ArrayList<Integer>()); //works
MyMethodUtils.invoke(student, "setMarks", "John", new ArrayList<Integer>()); // getMethod() method always cannot find a proper method
Is it impossible? Or is there ways to implement so?
Aucun commentaire:
Enregistrer un commentaire