码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-11-13 19:17:38      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:des   io   ar   os   sp   java   for   on   cti   

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方法

标签:des   io   ar   os   sp   java   for   on   cti   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!