通过Java的反射动态调用类的set和get方法

来源:互联网 发布:商城虚拟商品数据库 编辑:程序博客网 时间:2024/05/18 01:36
public static <T> void testGetOrSet(List<T> list) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{        Class tClass = list.get(0).getClass();        //获得该类的所有属性        Field[] fields = tClass.getDeclaredFields();        for(Field field:fields){            PropertyDescriptor pd = new PropertyDescriptor(field.getName(), tClass);            //获得set方法            Method method = pd.getWriteMethod();            method.invoke(list.get(0), new Object[]{"123"});            //获得get方法            Method get = pd.getReadMethod();            Object getValue = get.invoke(list.get(0), new Object[]{});            System.out.println("field:"+field.getName()+"---getValue:"+getValue);        }    }


0 0
原创粉丝点击