About method.invoke

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

About method.invoke
About =
About Kotlin
About attr_accessor
About Hinemos
About inheritance
About params
About Docker
About Rails 6
About form_for
About Spring ③
About enum
About polymorphism
About Optional
About hashes
About JitPack
About Dockerfile
About this ()
About devise
About encapsulation
About Docker
About JAVA_HOME
About active_hash
About static
About exceptions
About scope
[Maven] About Maven
Review about bundler
About Java interface
[Java] About Java 12 features
About Rails routing
About cyclomatic complexity
About exception handling
About AsyncTask Generics
About Ruby symbols
About array multiplication
[Java] About arrays
About HotSpot VM
About ruby ​​form
[Swift] About generics
About Active Storage
About class inheritance.
About Spring AOP
About Ruby Hashes
About singular methods
About getter setter
About build tools
About MacinCloud introduction
[Note] About nil
About keyword arguments
Chew about API
[About double hash]
About installing Cocoapods
Something about java
Where about java
About HttpServlet () methods
About Java features
About ActiveRecord :: PendingMigrationError
About SIGNING_REGION: NoSuchFieldError
About the method
About standard classes