Java gets call class methods and properties through reflection

Source: Internet
Author: User

First, what is reflection? Reflection is a set of APIs launched by Sun, which is located in Java.lang.reflect

The role of reflection is to write a tool (such as Eclipse), to write a framework, of course, for general programs, we can not use reflection to do these things, the general reflection is mostly used in the construction of class instances and call class methods and properties.

Ok! Knowing what reflection is and where it's applied, let's look at how reflection is implemented in Java.

Student class

 Public class Student {    public  String name;      Public String gender;      Public int Age ;          Public Student () {            }}

To get an instance of a class using reflection

PublicclassTest { Public Static voidMain (string[] args)throwsreflectiveoperationexception {//get class objects for classes in three waysClass<?> c=student.class; Class<?> c1=NewStudent (). GetClass (); Class<?> c2=class.forname ("Student");//gets the class object by the package name. Class name (because the class is in the default package, so the package name can not be written)//The Student instance is constructed from a class object, and the effect, like new Student (), requires that the constructor of the Student must have no parametersStudent s=(Student) c.newinstance (); Student S1=(Student) c1.newinstance (); Student S2=(Student) c2.newinstance (); S.age=1; S1.age=2; S2.age=3;        System.out.println (S.age);        System.out.println (S1.age);    System.out.println (S2.age); }

You can see that the correct output of the

The properties and methods of the class are obtained by reflection, and the dynamic execution

Student Type

 Public classStudent { PublicString name; Private intAge//This property is private and can be obtained by reflection         PublicStudent () {} Public intAddintAintb) {        returnA +b; } @Override PublicString toString () {//TODO auto-generated Method Stub        return"Name=" +name+ "\nage=" +Age ; }}

Dynamic assignment of properties to classes and methods of invoking classes

 Public classTest { Public Static voidMain (string[] args)throwsreflectiveoperationexception {//Get Class objectClass<?> c=class.forname ("Student"); //Gets the Property object for the class and needs to fill in the name of the Property objectField F1=c.getfield ("name");//objects that can only get publicField F2=c.getdeclaredfield ("Age");//can get to private object, this is very hanging barf2.setaccessible (true);//If the property is private, then you need to set the accessibleStudent s1=(Student) c.newinstance (); //Assigning a value to a Property objectF1.set (S1, "Zhang San"); F2.set (S1,22);                System.out.println (S1.tostring ()); //methods for getting classes from class objectsMethod M1=c.getmethod ("Add",int.class,int.class); //dynamic method of execution        intSum= (int) M1.invoke (S1,);                    SYSTEM.OUT.PRINTLN (sum); }}

Java gets call class methods and properties through reflection

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.