java利用反射执行字符串方法

来源:互联网 发布:马航mh370终结篇 知乎 编辑:程序博客网 时间:2024/06/06 01:17
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestMethod {
public static void main(String[] args) throws NoSuchMethodException,
SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
TestMethod testMethod = new TestMethod();
TestMethod.City city = testMethod.new City();
String name = "setName(成都)";
String code = "setCode(chengdu)";
testMethod.dotMethod(name, city);
testMethod.dotMethod(code, city);
System.out.println(city.getName() + "," + city.getCode());
}


private void dotMethod(String methodStr, Object obj)
throws NoSuchMethodException, SecurityException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
// 拆解方法字符串,找出方法名
String methodName = methodStr.substring(0, methodStr.indexOf('('));
// 找出参数
String[] args = null;
String paramStr = methodStr.substring(methodStr.indexOf('(') + 1,
methodStr.indexOf(')'));
if (!paramStr.isEmpty()) {
String[] tmp = paramStr.split(",");
args = tmp;
}
Class c = obj.getClass();
Method method = c.getMethod(methodName, String.class);
method.invoke(obj, args[0]);
}


public class City {
private String name;


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public String getCode() {
return code;
}


public void setCode(String code) {
this.code = code;
}


private String code;
}
}
阅读全文
0 0
原创粉丝点击