Analysis of Java Reflection mechanism

Source: Internet
Author: User

First, the understanding of reflection

Reflection is similar to the reflection of the plane mirror we see at ordinary times: the reflected target (any class of known name), the reflected "mirror" (Any class in our class object <java should have a class object >), through this "mirror", the class object, we can get the information of any known name class at run time.

Second, Java features provided by the reflection mechanism

Java The reflection mechanism mainly provides the following functions: To judge any exclusive class at runtime, to construct an object of any class at run time, to judge the member variables and methods of any class at run time, to invoke the method of any object at run time, to create a new class object at run time, to generate a dynamic proxy.

Java The reflection mechanism allows the program to load, detect, and use a completely unknown time during compilation. classes.

1 , Get class Object

A. Use Class the static method of the class. For example:class.forname ("java.lang.String");

B. using the class's . Class syntax. For example:string.class;

c. using the object's getclass () methods, such as:

String str = "AA"; class<?> ClassType = Str.getclass ();

getclass () method defines the Object class, it is not a static method, it needs to be called through an object, and it is declared as Final , indicating that the quilt cannot be overridden.


2 , gets the class's Fields

Java.lang.reflect.field[]fields=a.getclass (). GetFields ();

For example , Eclipse, write an object name, a click, will automatically pop up all the methods of the object, which uses the Java Reflection principle to get the properties and methods of the class.

3 , gets the class's Method

Importjava.lang.reflect.Method; Publicclass dumpmethods{public    static void Main (string[] args) throws Exception   {        //Get the class object identified by the string        class<?> ClassType =class.forname ("java.lang.String");//The string is passed here to specify the class name, so the parameter acquisition can be a run-time behavior, can be used args[0]              //Returns an array of all the methods declared in the class or interface corresponding to the class object (including private methods)        Method[] Methods =classtype.getdeclaredmethods ();               Traverse output All method declaration for        (method Method:methods)        {            System.out.println (method);        }    }}

4 , gets the class's Constructor

Use a constructor to instantiate beanconstructorconstructor = Clazz.getconstructor (New Class[]{string.class,string[].class}); sb = ( Simplebean) constructor.newinstance (newobject[]{"Liu Steaming", newstring[]{"football", "basketball"}); System.out.println (SB);

5 , an instance of the new class

Class<?>classtype = Extendtype.class;object Inst =classtype.newinstance (); SYSTEM.OUT.PRINTLN (inst);


6 , calling a function of a class

Class<?>classtype = Extendtype.class; Object Inst =classtype.newinstance (); Method logmethod =classtype.getdeclaredmethod ("Log", String.class); Logmethod.invoke (Inst, "Test");

7 , setting / Get property values for a class

Class<?>classtype = Extendtype.class; Object Inst =classtype.newinstance (); Field Intfield =classtype.getfield ("Pubintextendfield"); Intfield.setint (inst,100);   

Iii. Advantages and Disadvantages

Pros: You can implement dynamic creation of objects and compile-as-run-time determination types, binding objects.

Cons: Has an impact on performance. Using reflection is basically an interpretation operation, and we can tell the JVMWhat we want to do and it satisfies our requirements. This type of operation is always slower than performing the same operation directly.

Iv. Summary

         ifA,Bare developing classes, ifAyou want to useBwrite the class, butBnot finished, thenAThe code is not compiled. This time usingJavareflection mechanism, you can makeAin noBThe written class to complete the compilation of its own code.

Reflection provides a run-time load class that dynamically gets the name of the class, methods, properties, modifiers, and so on. Decoupling between programs, flexibility is great, code readability is good.

Analysis of 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.