1.若調(diào)用的函數(shù)所屬的類為自定義類,則將函數(shù)和類寫進(jìn)map中
Map methods = new HashMap();
methods.put("__plus","Param.tool");
2.通過將函數(shù)名稱獲取相應(yīng)的class,再獲取函數(shù)對象
Class c = Class.forName((String)methods.get(name.toString())); //通過函數(shù)名稱獲取對應(yīng)的類名,通過類名獲取類
Object obj = c.newInstance();
Method methods = c.getMethod(name.replace("__", ""), args.getClass()); //通過類對象獲取方法對象
3.調(diào)用函數(shù)
methods.invoke(obj, (Object)args);
注意:若傳遞的對象為數(shù)組時(shí),傳遞被認(rèn)為是多個參數(shù),導(dǎo)致wrong number of arguments異常
此處強(qiáng)制轉(zhuǎn)為一個Object對象即可
package Param;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.jmeter.functions.BeanShell;
public class CallMethod {
private static Map methods = new HashMap();
public CallMethod() {
????methods.put("__plus","Param.tool");
}
public static Object getMethod(String method) throws ClassNotFoundException, NoSuchMethodException,
????SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
????Matcher m = Pattern.compile("(__[a-z]{1,})\\((.*?)\\)").matcher(method.toLowerCase());
????String name = "";
????String[] args = new String[] {};
????while(m.find()) {
????????System.out.println(m.group());
????????name = m.group(1);
????????args = m.group(2).split(",");
????}
????Class c = Class.forName((String)methods.get(name.toString()));
????Object obj = c.newInstance();
????Method methods =? c.getMethod(name.replace("__", ""), args.getClass());
????System.out.println(methods.toString());
????return methods.invoke(obj, (Object)args);
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
CallMethod md = new CallMethod();
Object m = md.getMethod("__plus(1,2,3,4,5)");
System.out.println(m.toString());
}
}
相應(yīng)的加函數(shù)
package Param;
public class tool {
????public static String plus(String[] args) {
????????int sum =0;
????????for(int i=0;i<args.length;i++) {
????????????sum += new Integer(args[i]);
????????}
????????return "" + sum;
}