임의의 객체에 있는 모든 String 유형의 구성원 변수에 해당하는 문자열의 내용에서 "b"를 "a"로 변경
1994 단어 리플렉스
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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
비안의 속성을 반사하여 검사합니다최근에 인터페이스를 쓰고 있는데, 매개 변수는 하나의 대상으로 수신된다.객체의 등록 정보를 판단하려면 필수 항목이 필요합니다. 1、모든 속성명 획득 2. 속성 중의 값을 획득 3. 속성이null인지 판단...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.