首页 > 编程语言 > 详细

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

时间:2014-11-13 19:15:17      阅读:571      评论:0      收藏:0      [点我收藏+]
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);
		}
	}


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

原文:http://my.oschina.net/u/1866821/blog/344080

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!