方法类
public class Pub_Methods {
private String myString = "测试字符串";
public String getMyString() {
return myString;
}
public void setMyString(String myString) {
this.myString = myString;
}
}
反射动态调用
import org.junit.Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MyDemo {
@Test
public void test() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Pub_Methods pubMethods = new Pub_Methods();
Method method;
//所有类方法对象
Method[] methods = pubMethods.getClass().getMethods();
for (Method m:methods){
//只获取SET方法
if (m.getName().startsWith("set")){
System.out.print("方法名称:"+m.getName()+"\t");
System.out.println("参数类型:"+m.getParameterTypes()[0].getName());
}
}
//无参调用
method = pubMethods.getClass().getMethod("getMyString");
String myStr = (String) method.invoke(pubMethods);
System.out.println("无参调用返回结果:"+myStr);
//有参调用
method = pubMethods.getClass().getMethod("setMyString", String.class);
method.invoke(pubMethods,"新的参数值");
System.out.println("有参调用返回结果:"+pubMethods.getMyString());
}
}
输出结果:
方法名称:setMyString 参数类型:java.lang.String
方法名称:setMyList 参数类型:java.util.List
无参调用返回结果:测试字符串
有参调用返回结果:新的参数值