通过一个方法名字符串,来调用该名字如何实现?
例如,已知Class为Test,其中有方法setTax,参数为String tax; 怎么在程序中通过方法名及参数自动调用这个方法!!

解决方案 »

  1.   

    我们可以用 reflection 来做一些其它的事情,比如执行一个指定了名称的方法。下面的示例演示了这一操作:import java.lang.reflect.*;
    public class method2 {
        public int add(int a, int b) {
            return a + b;
        }
        public static void main(String args[]) {
            try {
                Class cls = Class.forName("method2");
                Class partypes[] = new Class[2];
                partypes[0] = Integer.TYPE;
                partypes[1] = Integer.TYPE;
                Method meth = cls.getMethod("add", partypes);
                method2 methobj = new method2();
                Object arglist[] = new Object[2];
                arglist[0] = new Integer(37);
                arglist[1] = new Integer(47);
                Object retobj = meth.invoke(methobj, arglist);
                Integer retval = (Integer) retobj;
                System.out.println(retval.intValue());
            } catch (Throwable e) {
                System.err.println(e);
            }
        }
    }
      

  2.   

    public static void main(String[] args) throws SecurityException,
        NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
        InvocationTargetException, NoSuchFieldException {
      Test test = new Test();
      Class clazz = Test.class;
      // 方法一:调用 setTax 方法
      Method method = clazz.getMethod("setTax", String.class);
      method.invoke(test, "abc");
      System.out.println(test.getTax());
      // 方法二:直接给 private 属性 tax 赋值,
      // 不通过 set 方法,Hibernate 就是类似这样做的
      Field field = clazz.getDeclaredField("tax");
      field.setAccessible(true);
      field.set(test, "123");
      System.out.println(test.getTax());
    }可恶的反射竟要抛出那么多的异常~~