Java reflection 2 dynamically call the method of the class

Person.java

package fanshe;

public class Person {
	private int age;
	private String name;
	
	private String info(){
		return "My name is "+ name +", I'm "+age+" years old.";
	}
	
	private void sayHellow(String word){
		System.out.println(word);
	}
}



Mymain.java

package fanshe;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Mymain {
	
	public static void main(String[] args) throws Exception{
		Mymain.invokeMethod("fanshe.Person", "sayHellow", "hellow");
	
	private static void invokeMethod (String className, String methodName, String value) throws Exception{
		Class clazz = Class.forName(className);
		Method mtd = clazz.getDeclaredMethod(methodName, String.class);
		mtd.setAccessible(true);
		mtd.invoke(clazz.newInstance(), value);
	}
}


Running result:
hello

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326696378&siteId=291194637