Private attributes and methods in Java classes

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.