Java反射 具体需求实现案例一

本文介绍如何使用反射技术在Java类中批量修改所有String字段中的'b'字符为'c'。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//需求把某个类的里所有的String字段中的所有b字母改成c,详见changeStringValue方法
import java.lang.reflect.Field;
class ReflectPoint {
	private int x;
	public int y;
	public String str1 = "ball";
	public String str2 = "body";
	public String str3 = "sun";
	public String str4 = "color";
	public ReflectPoint(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}
	
	@Override
	public String toString() {
		return "ReflectPoint [x=" + x + ", y=" + y + ", str1=" + str1
				+ ", str2=" + str2 + ", str3=" + str3 + ", str4=" + str4 + "]";
	}
	
}
public class Test {
	public static void main(String[] args) throws Exception {
		ReflectPoint pt = new ReflectPoint(3, 5);
		changeStringValue(pt);
		System.out.println(pt.toString());
	}
	private static void changeStringValue(Object obj) throws Exception {
		Field[] fields= obj.getClass().getFields();
		for(Field field: fields) {
			if(field.getType() == String.class) { //字节码比较 用等号比较好
				String oldValue = (String)field.get(obj);
				String newValue = oldValue.replace('b', 'c');
				field.set(obj, newValue);
			}
		}
	}

}
/*输出
true
true
 */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值