Use the reflection API to access the private member

xiaoxiao2021-03-06  130

In some special Java applications, it is possible to access or modify the private member of the class, and the Reflection API can help us do this.

Here is an example of modifying Private Field using the Reflection API. (Access private functions can also be used in a similar approach)

Suppose there is a class Dummy:

Public class dummy {

Public Int getValue () {

Return_Value;

}

Private int _Value = 0;

}

Need to change the value of the _value in the Dummy object to 1, you can use the following REFLECTION code:

Dummy d = new dummy ();

System.out.println (D.GetValue ());

Try {

Field f = d.getClass (). GetDeclaredfield ("_ value");

f.setAccessible (TRUE);

F.SET (D, New Integer (1));

F.setAccessible (FALSE);

} catch (nosuchfieldexception ex) {

// ...

} catch (IllegaCcessException ex) {

// ...

}

System.out.println (D.GetValue ());

Run the above program, you can see the _value value from 0 into 1.

The Class class also has a getField () method, but this method can only return to public Field. To access a member of Private or protected, you need to call getDeclared ... this series of methods. It is worth noting that the method of getDeclared ... only returns a member of the class directly declared, if you need to access the parent class, you need to get the Class object of the parent class, and then get a member object on the object.

To access the membership object, you also need to modify the status of its access control. Setaccessible (TRUE) allows us to access it. Setaccessible (false) is set to the default access control of Java.

Private members accessed using the Reflection API generally have two uses:

1. Implement a function of some subject, for example, store an object in an XML file and a function read it. This can be implemented using the Reflection API access object member, and the object is no longer need to meet some special requirements, such as implementing an interface or meeting the BEAN.

2. When inheriting an existing class, you need to access the PRIVATE member of the parent class in the subclass. Sometimes we can't modify the code of the parent class to protected the member to protected, so you have to use the Reflection API.

The second case is actually possible to be a design problem of the parent class. The design of the parent class should not interfere with the scope to expand it (Open-Close principles), and the members declared that Private will often affect this extensibility. This problem means that when designing, we should carefully use Private, more using protected to define private members.

Author: DaiJiaLin

Mailto: WoodyDai@gmail.com

http://blog.9cbs.net/daijiang

转载请注明原文地址:https://www.9cbs.com/read-100014.html

New Post(0)