임의의 객체에 있는 모든 String 유형의 구성원 변수에 해당하는 문자열의 내용에서 "b"를 "a"로 변경

1994 단어 리플렉스
1. 테스트된 클래스
package cn.sunft.day01.reflect;

/**
 *        ,      
 * @author sunft
 *
 */
public class ReflectPoint {
	
	private int x;
	public int y;
	public String str1 = "ball";
	public String str2 = "basketball";
	public String str3 = "itcast";
	
	
	public ReflectPoint(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	@Override
	public String toString() {
		return str1 + ":" + str2 + ":" + str3;
	}
	
}

테스트 클래스의 코드:
package cn.sunft.day01.reflect;

import java.lang.reflect.Field;

/**
 *       Field
 * @author sunft
 *
 */
public class FieldTest {

	public static void main(String[] args) throws Exception {
		ReflectPoint pt1 = new ReflectPoint(3, 5);
		//        public     
		Field fieldY = pt1.getClass().getField("y");
		//fieldY     ? 5, !fieldY         ,
		//    ,              
		System.out.println(fieldY.get(pt1));
		
		//     
		Field fieldX = pt1.getClass().getDeclaredField("x");
		fieldX.setAccessible(true);//     true
		System.out.println(fieldX.get(pt1));
		
		//   
		changeStringValue(pt1);
		//     
		System.out.println(pt1);
	}

	/**
	 *                     b     a
	 * @param obj
	 * @throws Exception
	 */
	private static void changeStringValue(Object obj) throws Exception {
		Field[] fields = obj.getClass().getFields();
		for(Field field : fields) {
			//if(field.getType().equals(String.class)) {
			//           ,      ==  ;
			//       ,      ==    
			if(field.getType() == String.class) {
				String oldValue = (String)field.get(obj);
				//       b   a
				String newValue = oldValue.replace('b', 'a');
				// obj   field    newValue  
				field.set(obj, newValue);
			}
			
		}
	}

}

콘솔 인쇄 결과:
5
3
aall:aasketaall:itcast

좋은 웹페이지 즐겨찾기