经过反射得到的属性名是一个完整的路径,我怎么得到的只是一个属性名呢。

解决方案 »

  1.   

    谁说的?package cn.forecast.test;
    public class TestReflect
    {
    public static Object execute(String className, String methodName,
    Object[] args) throws ClassNotFoundException,
    InstantiationException, IllegalAccessException, SecurityException,
    NoSuchMethodException, IllegalArgumentException,
    java.lang.reflect.InvocationTargetException
    {
    Object object = Class.forName(className).newInstance();
    Class[] argsClass = new Class[args.length];
    for (int i = 0; i < args.length; i++)
    argsClass[i] = args[i].getClass();
    java.lang.reflect.Method method = object.getClass().getDeclaredMethod(
    methodName, argsClass);
    java.lang.reflect.Field[] fs=object.getClass().getDeclaredFields();
    for(int i=0;i<fs.length;i++)
    System.out.println("Property "+i+" :"+fs[i].getName());
    return method.invoke(object, args);
    }
    public static void main(String[] args) throws SecurityException, IllegalArgumentException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, java.lang.reflect.InvocationTargetException
    {
    System.out.println(execute("cn.forecast.test.ABC", "theMethod", new Object[]{"hello",5}));
    }
    }class ABC
    {
    private String name;
    private String addr;
    String theMethod(String s,Integer i)
    {
    return s+i;
    }
    }
    运行一下看看得到的结果是什么?
      

  2.   

    谢谢 imA(男的不会,会的不男),问题解决了,我是用forName的方法得到的clazz就是全路径,换你的方法就行了,也不知道这两种方法有什么区别么。
      

  3.   

    我现在是有两个javaBean 比如 Employee和Factory,我在主函数里面创建两个它们的对象,给属性赋值。因为它们都是放在List里面的(list里面只放它们之一),因为取出来的对象不确定,所以要用反射取他们的对象和对应的属性值,这样该怎么弄啊。
      

  4.   

    上面的代码不是给你写了嘛,就那么弄啊。多查查api文档,什么都知道了。