Field class learning Java reflection to access and modify variables

Field class provides access to the properties and values ​​of class members a number of ways, the most common is to visit the member variable value and modify variable values.

As we all know, there is a variable modifier pubilc, access to protected, default, private, modifiers provide successively smaller, private modification can only access this class, however, can be accessed and modified by java.lang.reflet.Field class private modified private variables, example as follows:

 

Waiting to be accessed Person class and its variables:

public class Person {
    
    public String name = "graham";
    protected String sex = "男";
    String province = "天津";
    private int age = 26;

}

By Field class get (Object ojb) and set (Object ojb, Object value), access and modify the Person class altogether private members:

public class TestClass {
    public String aa ="aaa";
    private String bb = "bbb";
    protected String cc = "ccc";

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Person person = new Person();

        //访问公有成员用getField或者getDeclaredField
        Field field  = person.getClass().getField("name");
        field.set(person, "grahamliu");
        System.out.println(field.get(person));

        //Access to non-public members must getDeclaredField 
        Field, field1 = person.getClass () getDeclaredField ( "Sex." ); 
        Field1.set (the Person, "female" ); 
        System.out.println (field1.get (the Person)); 

        Field, Field2   person.getClass = () getDeclaredField ( "Province." ); 
        field2.set (the Person, "Antarctica" ); 
        System.out.println (field2.get (the Person)); 

        // accessed and modified private variables, you must set setAccessible is to true 
        Field, Field3 = person.getClass () getDeclaredField ( "Age." ); 
        field3.setAccessible ( to true ); 
        field3.set (Person, 87  );
        System.out.println (Field3.get(person));

         // access to the private variable class, without providing the setAccessible 
        Field, the TestClass = Field4. Class .getDeclaredField ( "CC" ); 
        System.out.println (field4.get ( new new the TestClass ())); 
    } 
}

print:

/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/bin/java "-javaagent:/Applications/IntelliJ IDEA 
grahamliu
女
南极
87
ccc

Process finished with exit code 0

 

Knowledge involves two points:

1. Access public members with getField or getDeclaredField, access to non-public members must getDeclaredField

2. Access and modification of private variables must be set setAccessible is true, except this class!

Guess you like

Origin www.cnblogs.com/u1s1/p/12435859.html