本帖最后由 唐志兵 于 2012-6-9 20:05 编辑
- import java.lang.reflect.Field;
- public class ReflectTest2 {
- public static void main(String[] args) throws Exception {
- changeString();
- }
- private static void changeString() throws Exception {
- // TODO Auto-generated method stub
- ReflectPoint rp = new ReflectPoint(5, 6);
- Field[] fields = rp.getClass().getFields();
- for (Field field : fields) {
- if (field.getType() == String.class) {
- //比较两份字节码是否相同,所以要用 == 而不用 equals
- //问题在这里: field.getType和 field.getClass返回的都是Class,它们有什么区别呢?
- String strOld = (String) field.get(rp);
- 怎么我把代码粘贴上来,前面的空格就没了呢,这样看太乱了。
- String strNew = strOld.replace("b", "hi,");
- field.set(rp, strNew);
- }
- }
- System.out.println(rp);
- }
- }
- class ReflectString {
- public String str1 = "bhaoma";
- public String str2 = "bnihao";
- public String str3 = "bwobuhao";
- public String toString() {
- return str1 +":" + str2 + ":" + str3;
- }
- }
复制代码 |