一、枚举类获得方法名,由传进来的nameMap字符串类型可获得方法名
package invoke;
public enum TranferToMethod {
name("nameMap","queryNameList"),
appointNo("appointNoMap","queryAppointNoList");
TranferToMethod(String param, String methodName) {
this.param = param;
this.methodName = methodName;
}
private String param;
private String methodName;
public static String getMethodName(String param){
TranferToMethod[] values = TranferToMethod.values();
for (TranferToMethod value : values) {
if(value.param.equals(param)){
return value.methodName;
}
}
return "";
}
}
二、反射主代码
package invoke;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class ReflectStudy {
public Map<String,Object> query(Map<String,Object> paramMap) throws Exception {
String queryType = (String) paramMap.get("queryType");
String methodName = TranferToMethod.getMethodName(queryType);
Map<String,Object> result = new HashMap<>();
try {
Method declaredMethod = ReflectStudy.class.getDeclaredMethod(methodName, Map.class);
//参数为方法名字符串和方法的入参类型
result = (Map<String, Object>) declaredMethod.invoke(this,paramMap);
//参数为方法所在的类,方法入参
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new Exception("没有此方法");
}
return result;
}
public Map<String,Object> queryNameList(Map<String,Object> map){
//编写业务代码返回
Map<String,Object> result = new HashMap<>();
result.put("flag","1");
result.put("data","操作成功");
return result;
}
public Map<String,Object> queryAppointNoList(Map<String,Object> map){
//编写业务代码返回
return null;
}
}
三、利用反射对对象属性进行更改
public static void main(String[] args) throws Exception {
Tuser tuser = new Tuser("张三","男","25");
Field age = tuser.getClass().getDeclaredField("age");
age.setAccessible(true);
age.set(tuser,"28");
System.out.println("得到的用户为:"+tuser.toString());
}
得到结果为