java用Method执行字符串方法
//参考测试装配方法
public static void main(String[] args) {
SamplingFormDTO samplingForm=new SamplingFormDTO();
try{
String top = "setTop(23.1)";
dotMethod(top,samplingForm);
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* 由于坐标点字段较多,采用反射解析方法解决这个问题
* @param methodStr 方法名称
* @param obj 参数
* @throws NoSuchMethodException
* @throws SecurityException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*/
private void dotMethod(String methodStr,Object obj) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
//拆解方法字符串,找出方法名
String methodName = methodStr.substring(0, methodStr.indexOf('('));
//找出参数
float[] args = null;
String paramStr = methodStr.substring(methodStr.indexOf('(') + 1,methodStr.indexOf(')'));
if(!paramStr.isEmpty()){
String[] tmp = paramStr.split(",");
args = new float[tmp.length];
args[0] = Float.parseFloat(tmp[0]);
}
Class c = obj.getClass();
Method method = c.getMethod(methodName, float.class);
//注意invoke的参数别写错了,你的方法是什么类型,invoke就传什么类型参数
method.invoke(obj, args[0]);
}
}