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);
}
}IT资源下载 http://www.libre-free.com/
通过Java的反射动态调用类的set和get方法
最新推荐文章于 2024-04-15 10:56:50 发布
本文通过一个具体的Java代码示例展示了如何使用反射机制获取并设置类的属性值。该示例涉及获取类的所有字段、使用PropertyDescriptor创建getter和setter方法,并调用这些方法来设置和获取属性。

1万+

被折叠的 条评论
为什么被折叠?



