Javaの反射による動的呼び出しクラスのsetとgetメソッド

718 ワード

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);
		}
	}