利用反射机制将字符中的某个字符换成另一个字符

此例子:将字符为b的换成a:

 

public class ReflectChangeValue {
	public String  str1 = "boll";
	public String str2 = "basketball";
	public String str3 = "zchen";
	
	@Override
	public String toString() {
		
		return str1+"--"+str2+"--"+str3;
	}
}

 

 

import java.lang.reflect.Field;

public class ReflectTest {
	
	public static void main(String[] args) throws Exception {
		ReflectChangeValue rf = new ReflectChangeValue();
		
		changeStringValue(rf);
		System.out.println(rf);    
		/**String str1 = "abc";
		Method methodCharAt = String.class.getMethod("charAt", int.class);
		System.out.println(methodCharAt.invoke(str1, 1));*/
	}
	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', 'a');
				field.set(obj, newValue);
			}
		}
	}
}

你可能感兴趣的:(反射机制)