Reflection member variables of Java's reflection

Previous describes the structure of the Java reflection reflection method . This time we talk about how the reflection member variables in class and used as a simple case.

[A] Class Field,

Filed class represents the field that contains all of the fields have properties, such as modifiers, variable type, value, etc., Filed class has a method to obtain these properties.
And Constructor classes inherit as a java.lang.reflect.AccessibleObject class, there are ways to determine whether the access and set up private property.
For the following shows how to modify, to get a class variable:
Point class:

public class Point {
    public int x;
    private int y;
    public static int z = 10;
    
    public Point(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }
    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }
}

Test Methods:

public static void main(String[] args) throws Exception {
        Point p = new Point(3,4);
        Class cls = p.getClass();
        //1、获得Point类中所有的成员变量
        Field[] fields = cls.getFields();
        //打印
        for(Field field : fields){
            //get(p);获得对象p的所有成员变量
            System.out.println(field.get(p));
        }
        
        //2、获得Point类中的指定x,y,z变量
        Field fieldX = cls.getField("x");
        Field fieldY = cls.getField("y");
        Field fieldZ = cls.getField("z");
        //分别对应对象p
        System.out.println("x:"+fieldX.get(p)+" y:"+fieldY.get(p)+" z:"+fieldZ.get(null));
        
    }

result:

3
10
Exception in thread "main" java.lang.NoSuchFieldException: y
    at java.lang.Class.getField(Class.java:1584)
    at club.leyvan.muzile.ConstructDemo.main(ConstructDemo.java:20)

GetFields Class class (): get all fields such as the object of the Field class.
Class class getFields (String name): to obtain the class and parameters field of the same name.
Filed class get (p): This field is which bind a target body. Examples of the pass p, the target binding member field to field corresponding to the specific object and is a p p value object name of the field in the object representing the method.
Static variables belonging to the class so do not need to bind a specific object, you can get a static field pass null value.
The first part of the code in addition to private variables are printed out, and the second part of the report was wrong, not the private variable y, we can see that being a private variable can not be read. We now put the following code changes, you can get the value of a private variable.
Code is modified as follows:

public static void main(String[] args) throws Exception {
        Point p = new Point(3,4);
        Class cls = p.getClass();
        //1、获得Point类中所有的成员变量
        Field[] fields = cls.getFields();
        //打印
        for(Field field : fields){
            //get(p);获得对象p的所有成员变量
            System.out.println(field.get(p));
        }
        
        //2、获得Point类中的指定x,y,z变量
        Field fieldX = cls.getField("x");
        //修改部分↓↓
        Field fieldY = cls.getDeclaredField("y");
        fieldY.setAccessible(true);
        //修改部分↑↑
        Field fieldZ = cls.getField("z");
        //分别对应对象p
        System.out.println("x:"+fieldX.get(p)+" y:"+fieldY.get(p)+" z:"+fieldZ.get(null));
        
    }

result:

3
10
x:3 y:4 z:10

Class class getDeclaredField (String name): get private variables
Field class inherits class java.lang.reflect.AccessibleObject have setAccessible (boolean b): Set whether access to private members.
The above method called reflective violence, violence can get private members.

[Di] Case: reflection manner using a class variable of type String all "b" modify "a"

Bean categories:

package club.leyvan.muzile;

public class Bean {
    public int i1 = 10;
    public String str1 = "basketball";
    private String str2 = "breakfast";
    private static String str3 = "bbc";
    @Override
    public String toString() {
        return "Bean [i1=" + i1 + ", str1=" + str1 + ", str2=" + str2 + "]";
    }
    
    public static String getStr3(){
        return "str3: "+str3;
    }
}

Test Methods:

public static void main(String[] args) throws Exception {
        //获得class
        Class cls = Class.forName("club.leyvan.muzile.Bean");
        //创建一个对象 默认调用无参构造方法
        Bean obj = (Bean)cls.newInstance();
        //获得所有字段
        Field[] fields = cls.getDeclaredFields();
        //扫描所有字段
        for(Field field : fields){
            //class对象只有一份,所以使用==更好
            if(field.getType() == String.class){
                //判断是否是
                if(!field.isAccessible()){
                    field.setAccessible(true);
                }
                //判断是否是静态字段
                //getModifiers()获得所有的修饰符
                //boolean isStatic = Modifier.isStatic(field.getModifiers());
                String oldValue = (String)field.get(obj);
                String newValue = oldValue.replace('b', 'a');
                field.set(obj, newValue);
            }
        }
        System.out.println(obj+Bean.getStr3());
    }

result:

Bean [i1=10, str1=aasketaall, str2=areakfast]str3: aac

Wherein field.getModifiers (): get all modifiers
Modifier.isStatic (): determining whether modifier is obtained by static
field.set (obj, value): modify the value of the bound object

Next we say reflection of the members of the Java reflection method

Guess you like

Origin www.cnblogs.com/leyvan/p/12461699.html
Recommended