JAva反射-Field


package reflect;

import java.lang.reflect.Field;

public class ReflectionTest {
	
	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws Exception {
		
		Point point = new Point("AAA", "BBB");
		//Field field = cls.getDeclaredField("x");	// 
		Field fieldx = point.getClass().getDeclaredField("x");	// 
		fieldx.setAccessible(true);	// java 
		System.out.println(fieldx.get(point));	// x 
		
		modifyString(point);
		
		System.out.println(fieldx.get(point));
	}
	public static void modifyString(Object obj) throws Exception {
		Field[] fields = obj.getClass().getDeclaredFields();// , 、 、 ( ) , 。
		if(fields != null && fields.length>0) {
			for(Field field : fields) {
				if(field.getType() == String.class) {	// 
					field.setAccessible(true);
					String oldStr = (String)field.get(obj);
					String newStr = oldStr.replace('A', 'B');
					field.set(obj, newStr);
				}
			}
		}
	}
}