As you know, the methods or attributes modified by the private modifier in Java can only be accessed within this class, and cannot be accessed by other classes. Is that true? The following example can be used to access the private method in a class. The principle is that the reflection mechanism of Java seems insecure at this point.
A class with only one private method:
- Package net. Moon. Demo. Reflect;
- Public ClassPrivatemethod {
- PrivateString sayhello (string name ){
- Return "Hello ,"+ Name;
- }
- }
To call the private sayhello in the privatemethod class.
- PackageNet. Moon. Demo. Reflect;
-
-
- ImportJava. Lang. Reflect .*;
-
-
- Public ClassCallprivatemethod {
-
- Public Static VoidMain (string [] ARGs ){
-
- Try{
- Class C = Class. forname ("Net. Moon. Demo. Reflect. privatemethod");
-
- Method M = C. getdeclaredmethod ("Sayhello", String.Class);
-
- M. setaccessible (True);
-
- System. Out. println (M. Invoke (C. newinstance (),"Moon"));
- }Catch(Exception e ){
-
- System. Out. println (E );
-
- }
-
- }
-
- }
Compile and execute, and you will see a miracle.