最近程序里频繁用到反射,我想向大家求个通用的几个函数类
1.通过名字动态调用对象的字段,并获取其值2.通过名字动态获取对象的方法,并调用,返回其结果(包括函数和方法)

解决方案 »

  1.   

    小弟我自己写了一个很笨拙的函数 望大家指点改良下class Invoke
    {
    public static void  reflectCall(Object obj,String methodName,Class[] types,Object[] objs) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
    {

    Method  callMethod=obj.getClass().getMethod(methodName, types);


    callMethod.invoke(obj, objs);


    }

    public static void main(String args[]) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException
    {
    test temp=new test();


    reflectCall(temp,"print", new Class[] {String.class},new Object[]{"1"});
    }

    }class test
    {
    public void print(String i)
    {
    System.out.println("atswtewtw");
    } public void print(int i)
    {
    System.out.println(i);

    }
    }