Reflection in Java, knowing the class name creates a class, and you can set the value of a private property

Source: Internet
Author: User

Just learned the reflection, feel the function of reflection is very strong, so want to write a blog record of their own learning results.

Use reflection to create objects.

Class c1=class.forname ("Test. Person ");//create a class from the class name, where Test.person is just a class name. This person class code is//At the bottom of this article/*** Scenario 1: Call the parameterless constructor to create the object*/Person P=c1.newinstance ();//this creates it./*** Scenario 2: Calling a method with a parameter constructor*/Constructor CS=c1.getconstructor (String.class,int.class);//what is written in parentheses is the class of the parameter types of the constructor method, which is the addition of the following. class.Person p= (person) cs.newinstance ("Zhang San", 22);//invoking a constructor method to build an object
View Code

Use reflection to set private properties

    Try {    Class clazz=class.forname ("Testperson");    Person P=(person) clazz.newinstance ();    Field F1=clazz.getdeclaredfield ("name");    F1.setaccessible (true); // set whether private properties    can be manipulated F1.set (P, "WFADF"); System.out.println (F1.get (P));     Catch (Exception e) {        //  TODO auto-generated catch block        throw  New  runtimeexception (e);    }

Person Class Code

 Packagetest; Public classPerson {PrivateString name; Private intAge ;  PublicPerson () {} PublicPerson (String name,intAge ) {             This. Name =name;  This. Age =Age ; }     PublicString GetName () {returnname; }/*Public void SetName (String name) {this.name = name; }*/     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }}

Reflection in Java, knowing the class name creates a class, and you can set the value of a private property

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.