In other classes, you cannot obtain the private attribute and access the private method in the class. However, there is no way to do this. The powerful reflection mechanism of Java can complete this task.
Create a test Class:
Package COM. shao. test; </P> <p> Public Class A {<br/> private string teststr = "just for test"; <br/> private void get (INT index, string Value) {<br/> system. out. println (index + ":" + value + "and teststr:" + teststr); <br/>}< br/>
Now let's access the teststr attribute and get method in:
Package COM. shao. test; </P> <p> Import Java. lang. reflect. field; <br/> Import Java. lang. reflect. invocationtargetexception; <br/> Import Java. lang. reflect. method; </P> <p> Public Class B {<br/> Public static void main (string [] ARGs) throws classnotfoundexception, nosuchfieldexception, expiration, illegalaccessexception, nosuchmethodexception, invocationtargetexception {<br/> Field field = Class. forname ("com. shao. test. A "). getdeclaredfield ("teststr"); <br/> field. setaccessible (true); <br/> A = new A (); <br/> system. out. println (field. getType (). tostring (); // print: Class Java. lang. string <br/> system. out. println (field. getname (); // print: teststr <br/> system. out. println (field. getmodifiers (); // print: 2 <br/> Object S = field. get (a); <br/> system. out. println (s); // print: Just for test <br/> string x = "hello"; <br/> field. set (A, x); <br/> system. out. println (field. get (a); // print: Hello <br/> method = Class. forname ("com. shao. test. A "). getdeclaredmethod ("get", new class [] {Int. class, String. class}); <br/> method. setaccessible (true); <br/> method. invoke (A, 3, "Apples"); // print: 3: Apples and teststr: Hello <br/>}< br/>
The property is obtained using the filed class, and the method class is used to call the property.