首页 > 代码库 > Java在利用反射条件下替换英文字母中的值

Java在利用反射条件下替换英文字母中的值

(1)创建两个Class:

ReflectTest类如下:

package cn.itcast.day01;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class ReflectTest {

	
	public static void main(String[] args) throws Exception {
		
		changeStringValue(pt1);
		System.out.println(pt1);
	}
			
	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){  //同一个字节码用等号  而不是用equal
					
				String oldValue = http://www.mamicode.com/(String) field.get(obj);>
ReflectPoint类如下:

package cn.itcast.day01;

public class ReflectPoint {

	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 String toString(){
		return str1+":"+str2+":"+str3;
		
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}

结果为:aall:aasketaall:itcast