"Go" "Java" using reflection technology, to implement the private method of the class, variable access

Source: Internet
Author: User

Java's package of reflection mechanisms is mainly in java.lang.reflect, and structs,hibernate,spring frameworks are based on the reflection mechanism of java.

Here is a simple example of using Java's reflection mechanism to access private properties and private methods, and hopefully it will help you.

ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method;Importjava.util.ArrayList; Public classPerson {PrivateString name;//Private Properties     PublicString address;  PublicPerson (String name) { This. name=name; }               Private voidSetaddress (String address) {//Private Methods         This. address=address; }                Public Static voidMain (string[] args) {Try{ person person=NewPerson ("Zhangsan"); Class<Person> Cls=person.class; //Get Private methodsMethod Method=cls.getdeclaredmethod ("Setaddress",NewClass[]{string.class}); //setting private methods can be accessedMethod.setaccessible (true); //Calling Private MethodsMethod.invoke (Person,Newobject[]{"BJUT"}); System.out.println (person.address);//Output Bjut//Accessing private variablesField Field=cls.getdeclaredfield ("name"); Field.setaccessible (true); Field.set (person,"Test China"); System.out.println (Field.get (person));//Output ZhangsanArrayList<String> test =NewArraylist<string> (1000); Class<ArrayList> tcls = ArrayList.class; Field= Tcls.getdeclaredfield ("Size"); Field.setaccessible (true); Field.set (Test,100);                         System.out.println (Field.get (test));                     System.out.println (Test.size ()); }Catch(Exception ex) {ex.printstacktrace (); }                }          Public classTest {PrivateString name;//Private Properties    } }

From: http://zc0604.iteye.com/blog/1168859

"Go" "Java" using reflection technology, to implement the private method of the class, variable access

Related Article

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.