java 反射 Field类
-------用到一个bean
- package com.ncs;
-
- public class Point {
-
- private int x;
- public int y;
-
- public Point(int x, int y) {
- super();
- this.x = x;
- this.y = y;
- }
-
- }
--------------------
- package com.ncs;
-
- import java.lang.reflect.Field;
-
-
- public class ReflectTest {
-
- public static void main(String[] args) throws Exception {
-
- Point pt1 = new Point(3,5);
-
-
- Field fieldY = pt1.getClass().getField("y");
-
-
-
-
- System.out.println(fieldY.get(pt1));
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Field fieldX = pt1.getClass().getDeclaredField("x");
- fieldX.setAccessible(true);
- System.out.println(fieldX.get(pt1));
-
-
-
-
- }
- }
---------------------------下面做的小实验,把一个类里所有String类型的字段里的值 b 变 a
- package com.ncs;
-
- public class Point {
-
- private int x;
- public int y;
-
- public String s1 ="ball";
- public String s2="hubin";
- public String s3="zhangxiaoxiang";
-
-
- public Point(int x, int y) {
- super();
- this.x = x;
- this.y = y;
- }
-
- }
----------------------------
- package com.ncs;
-
- import java.lang.reflect.Field;
-
-
- public class ReflectTest {
-
- public static void main(String[] args) throws Exception {
-
- Point pt1 = new Point(3,5);
-
-
- Field[] fields = pt1.getClass().getFields();
-
- for(Field field : fields ) {
-
-
-
- if(field.getType()== String.class) {
- String oldValue = (String)field.get(pt1);
- String newValue = oldValue.replace('b', 'a');
-
- field.set(pt1, newValue);
-
- }
- }
-
- System.out.println(pt1.s1);
- System.out.println(pt1.s2);
- System.out.println(pt1.s3);
-
-
-
-
-
- }
- }
-----------------------------
|