Java Reflection mechanism

Source: Internet
Author: User

During the loading phase of the class file, the virtual machine stores the class information in the method area data structure and generates a class object in the Java heap as the entry for the class information.

If you write a piece of code: Object O=new object ();

Run it Up!

First the JVM will start, your code will be compiled into a. class file, then loaded into the JVM's memory by the ClassLoader, your class object is loaded into the method area, the object class object is created into the heap, note that this is not the new objects, Instead, the type object of the class, each class has only one class object, as an interface to the data structure of the method area class . Before the JVM creates the object, it checks to see if the class is loaded, finds the class object, and, if it is loaded, allocates memory for your object and initializes the code: new Object ().

Reflection contains an "inverse" concept, so to interpret reflection must begin with "positive": in general, when a user uses a class, they should know the class first, and then generate the instantiated object through this class.

But "anti" refers to finding classes through objects.

 Package cn.design.factory;  Public class reflacttest {    publicstaticvoid  main (string[] args) {        benzsport BS =new  benzsport ();        System.out.println (Bs.getclass (). GetName ());}    }

The above code uses a GetClass () method, and then can get the "package. Class" Name of the object, which is "anti", but in this "counter" operation there is a getclass () as the beginning of all the reflection operations initiated.

The parent class of Benzsport is the object class, and the GetClass () method used above is the method defined in the object class.

Get Class object: Public final class<?> getclass (), all generics in reflection are defined as?, and the return value is object.

The object returned by this getclass () method is the class object (the class object in the heap is the interface of the method area data interface) so this class is the source of all the reflection operations.

But there is one more question to explain before explaining its true use, since class is the source of all reflection operations, and this class is certainly the most important.and if you want to get an instantiated object of this class, three ways are defined in Java:
Method One: Obtained by means of the GetClass () method of the object class, basically without:
 Package cn.design.factory;  Public class reflacttest {    publicstaticvoid  main (string[] args) {        benzsport BS =new benzsport (); // getting an object        from a class Class<?> C=bs.getclass (); // getting class objects        from objects System.out.println (c); // come back.     }}

Mode two: Use "class. Class" To be used in the future when learning hibernate development

 Package cn.design.factory;  Public class reflacttest {    publicstaticvoid  main (string[] args) {        benzsport BS =new benzsport (); // getting an object        from a class Class<?> C=benzsport. class; // getting class objects        from objects System.out.println (C.getname ()); // come back.     }}

Method Three: Use a static method defined internally by the class classes, primarily using

public static class<?> forname (String className) throws ClassNotFoundException

 Package cn.design.factory;  Public class reflacttest {    publicstaticvoidthrows  Exception {        Benzsport bs=new  benzsport ();                Class<?> c=class.forname ("Cn.design.factory.BenzSport");                System.out.println (C.getname ());}    }

What is the use of a class object? The instantiation of an object has been done by using the constructor method and the keyword new, but with the class object, it now provides an instantiation of another object:

 Packagecn.design.factory; Public classReflacttest { Public Static voidMain (string[] args)throwsException {benzsport bs=NewBenzsport (); Class<?> C = class.forname ("Cn.design.factory.BenzSport");//Get Class Objects (object objects)Object o=c.newinstance ();//instantiating an object is as useful as newBenzsport bbs= (benzsport) o;//change down to the type you wantSystem.out.println (BBS); }}

Deep application of Reflection

The above only uses the class as the basic application of the reflection instantiation object, but for an instantiated object, it needs to invoke the constructor method, the common method, the property in the class, and these operations can be done through the reflection mechanism.

One: Call construction method

 Packagecn.design.factory;ImportJava.lang.reflect.Constructor; Public classReflacttest { Public Static voidMain (string[] args)throwsException {benzsport bs=NewBenzsport (); Class<?> C = class.forname ("Cn.design.factory.BenzSport");//Get Class Objects (object objects)Constructor<?> con[]=c.getconstructors ();//get all the construction methods         for(inti=0;i<con.length;i++) {System.out.println (con[i]); }            }}

If there is no parameterless construction method in the reflected class, the error will be

 Package cn.design.factory; Import Java.lang.reflect.Constructor;  Public class reflacttest {    publicstaticvoidthrows  Exception {                Class<?> C = class.forname ("Cn.design.factory.BenzSport"); // Get Class Objects (object objects)        Object o=c.newinstance ();}            }

 package   cn.design.factory;  import   Java.lang.reflect.Constructor;  public  class   reflacttest { public  static  void  main (string[] args)  Throws   Exception {Class  <?> c = Class.forName ("Cn.design.f Actory. Benzsport "); //         Gets the class object (object)  Constructor<?> cons=c.getconstructor (String.        Class   =cons.newinstance ("C-Level coupe" 

It is obvious that it is simpler and more convenient to invoke the parameterless construction method than to invoke the parameter structure, so in all future development, there must be a non-parametric structure in all the areas where there are simple Java classes.

Second: Call the normal method

 Packagecn.design.factory;ImportJava.lang.reflect.Method; Public classReflacttest { Public Static voidMain (string[] args)throwsException {Class<?> C = class.forname ("Cn.design.factory.BenzSport");//Get Class Objects (object objects)Method Meths[]=c.getmethods ();//get all the methods in a class including the methods of their own classes and the methods of the parent class         for(inti=0;i<meths.length;i++) {System.out.println (meths[i]); }    }}

 Packagecn.design.factory;ImportJava.lang.reflect.Method; Public classReflacttest { Public Static voidMain (string[] args)throwsException {Class<?> C = class.forname ("Cn.design.factory.BenzSport");//Get Class Objects (object objects)Object obj=c.newinstance (); Method Runmet=c.getmethod ("Run");//call the Run methodRunmet.invoke (obj);//call the No Argument method run ()String attr= "Name"; Method Setmet=c.getmethod ("Set" +attr, String.class);//Call the Set (String) methodMethod Getmet=c.getmethod ("get" +attr);//Call the string Get () methodSetmet.invoke (obj, "Mercedes Benz");            System.out.println (Getmet.invoke (obj)); }}

In all future framework technology development, the simple Java class is so applied, so it must be done according to the standard.

Three: Calling members

 Packagecn.design.factory;ImportJava.lang.reflect.Field; Public classReflacttest { Public Static voidMain (string[] args)throwsException {Class<?> C = class.forname ("Cn.design.factory.BenzSport");//Get Class Objects (object objects)Field Field[]=c.getdeclaredfields ();//Get all Properties         for(inti=0;i<field.length;i++) {System.out.println (field[i]); }    }}

 Packagecn.design.factory;ImportJava.lang.reflect.Field; Public classReflacttest { Public Static voidMain (string[] args)throwsException {Class<?> C = class.forname ("Cn.design.factory.BenzSport");//Get Class Objects (object objects)Field Field[]=c.getdeclaredfields ();//Get all Properties for(inti=0;i<field.length;i++) {System.out.println (field[i]);} Object obj=c.newinstance ();//Object Instantiation property will not allocate spaceField Namefield=c.getdeclaredfield ("name"); Namefield.setaccessible (true);//de-EncapsulationNamefield.set (obj, "Ling ye June");//the object. Name= "Ling ye June"System.out.println (Namefield.get (obj));//object. Name}}

Java Reflection mechanism

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.