We all know that the private variable is inaccessible, and a compile error can not be accessed at all. This article teaches you how to crack this limitation.
The principle of implementation is to take advantage of the reflection mechanism of java.
The simplest class is defined first, with only one private variable and one public method. The code is as follows:
class Foo { private String message = "This is a Foo." ; Public void Show () { System.out.println (message);
Normally, calling the show function outputs "This isa Foo." The following code bypasses Java's permission detection through the Setaccessible method.
Class<foo> Fooclass = (class<foo>= Fooclass.getdeclaredfield ("message"); Messagefield.setaccessible (true// bypass permission detection!)
Setaccessble accepts a Boolean parameter,true means bypassing the Java permission Detection mechanism, andfalse means that permission detection is enabled. Setaccessible (True) is called above so that Java does not detect permissions when it accesses. This method requires the virtual machine's reflectpermission ("suppressaccesschecks") permission when it is called.
Why do you want to access private variables? Because sometimes it is necessary to access the private variables when serializing.
Access to private methods is similar. However, this code should not be used too much, otherwise it will cause the program confusion, can not be maintained.
The following is the complete code:
Importjava.lang.reflect.*; Public classAccessprivate { Public Static voidMain (string[] argv)throwsException {//define a Test objectFoo foo =NewFoo (); //normal condition, test functionfoo.show (); //bypassing Java permission detectionClass<foo> Fooclass = (class<foo>) Foo.getclass (); Field Messagefield= Fooclass.getdeclaredfield ("message"); Messagefield.setaccessible (true);//Bypass Permission Detection! System.out.println ("Foo is hacked!"); //Modify the message variableMessagefield.set (foo, "This is a Bar.")); //call the test function againfoo.show (); } } classFoo {PrivateString message = "This is a Foo."; Public voidShow () {System.out.println (message); } }
In addition, there is a way to do this by writing the native library because all access in native does not require permission detection.
How Java accesses private variables