美文网首页工作生活
Java:反射调用类的函数

Java:反射调用类的函数

作者: ling67_ | 来源:发表于2019-07-01 15:22 被阅读0次

    1.若调用的函数所属的类为自定义类,则将函数和类写进map中

    Map methods = new HashMap();

    methods.put("__plus","Param.tool");

    2.通过将函数名称获取相应的class,再获取函数对象

    Class c = Class.forName((String)methods.get(name.toString())); //通过函数名称获取对应的类名,通过类名获取类

    Object obj = c.newInstance();

    Method methods = c.getMethod(name.replace("__", ""), args.getClass()); //通过类对象获取方法对象

    3.调用函数

    methods.invoke(obj, (Object)args);

    注意:若传递的对象为数组时,传递被认为是多个参数,导致wrong number of arguments异常

    此处强制转为一个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());

    }

    }

    相应的加函数

    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;

    }

    相关文章

      网友评论

        本文标题:Java:反射调用类的函数

        本文链接:https://www.haomeiwen.com/subject/qdwgcctx.html