I didn't have the opportunity to call and use the method dynamically, but I was curious to see it in the source code, so I put it into practice.
I created a class for confirmation and tried it. Here, the Invoke class receives the method name of the Getmethod class and calls it dynamically. It seems that we can do various things if we devise more, but first of all, the purpose is to move our hands and make them remember.
class Getmethod {
public void a(){
System.out.println("Called A");
}
public void b(String str){
System.out.println(str + "Called");
}
public void c(String str,String str2){
System.out.println(str + "When" + str2 + "Called");
}
}
public class Invoke {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
try {
//Get class
Class<?> g = Class.forName("invoke.Getmethod");
//Get an instance
Object myobj = g.newInstance();
//Get method
Method a = g.getMethod("a");
Method b = g.getMethod("b",String.class);
Method c = g.getMethod("c",String.class,String.class);
//Method execution
a.invoke(myobj);
b.invoke(myobj,"b");
c.invoke(myobj,"c","d");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Below is the execution result.
Called A
Called b
Called c and d
How to use If you have such a usage, we are waiting for an edit request.
Recommended Posts