Java Reflection mechanism

Source: Internet
Author: User

Objective

Today we introduce the reflection mechanism of Java, we used to get an instance of a class using the new instance. That is too low, today with me to learn to learn a more tall way to achieve.

Body Java Reflection Mechanism definition

The Java reflection mechanism is that in the running state, for any class, you can know all the properties and methods of the class, and for any object, it can call any of its methods and properties; This dynamically acquired information and the ability to dynamically invoke the object's methods are called the reflection mechanisms of the Java language.
In a nutshell, reflection enables you to know the properties and methods of any class at run time.

Advantages and disadvantages of reflection mechanism

Why use a reflection mechanism? Creating objects directly doesn't make sense, which involves the concept of dynamic and static

    • Static compilation: Determines the type at compile time, binds the object, which is passed.
    • Dynamic compilation: The runtime determines the type, binding object. Dynamic compilation maximizes the flexibility of Java and embodies the application of polymorphism, which reduces the coupling between classes.

    • Advantages
      can achieve dynamic creation of objects and compilation, showing great flexibility, especially in the development of Java EE, its flexibility is very obvious. For example, a large-scale software, it is impossible to design the perfect one at a time, when the program compiled, released, when the discovery needs to update some features, we can not want users to uninstall the previous, and then reinstall the new version, if so, this software is certainly not many people use. Using static words, the entire program needs to be recompiled once to achieve the function of the update, and the use of reflection mechanism, it can not uninstall, only need to be dynamically created and compiled at run time, you can implement this function.

    • Disadvantages
      Have an impact on performance. Using reflection is basically an interpretation operation, and we can tell the JVM what we want to do and it satisfies our requirements. This type of operation is always slower than just performing the same operation directly.
Understanding class classes and class types

To understand reflection first understand the class, which is the basis of the reflection implementation.
The class is an instance object of the Java.lang.Class class, and class is the classes of all classes (there is a-class named Class)
For ordinary objects, we will typically create and represent this:

Code CODE1 = new Code ();

It says that all classes are objects of class, so how do you do that, in the following ways:

Class C = new Class ();

But when we look at the source of the class, it's written like this:

Private  Class (ClassLoader loader) {     ClassLoader = loader;}

  

You can see that the constructor is private, and only the JVM can create class objects, so it is not possible to new class objects like normal classes, although we cannot new a class object, but we can get a class object from an existing class, there are three ways, as follows:

Class C1 = Code.class; This means that any class has an implied static member variable class, which is obtained by obtaining the class's static member variable class C2 = Code1.getclass (); Code1 is an object of Code, which is obtained by means of the GetClass () method of the object of a class C3 = Class.forName ("Com.trigl.reflect.Code"); This method is called by the class class to invoke the Forname method, which is obtained by the full qualified name of a class

  

Here, C1, C2, and C3 are all class objects, they are exactly the same, and have a scientific name, called the class type of code.
Here is strange, the front is not to say code is the object of class, and C1, C2, C3 is also the object of class, then code and c1, C2, C3 is not the same? Why is it called code what kind of type? Don't dwell on whether or not they are the same, as long as you understand what the class type is doing, as the name implies, the class type is the type of the class, that is, describe what a class is, what it is, so we can know the properties and methods of a class by the class type, and can invoke the properties and methods of a class. This is the basis of reflection.

To give a simple example code:

public class Reflectdemo {public    static void Main (string[] args) throws ClassNotFoundException {        //First type: Class C1 = Code.class;        Class Class1=reflectdemo.class;        System.out.println (Class1.getname ());        The second type: Class C2 = Code1.getclass ();        Reflectdemo demo2= new Reflectdemo ();        Class C2 = Demo2.getclass ();        System.out.println (C2.getname ());        The third type: Class C3 = Class.forName ("Com.trigl.reflect.Code");        Class CLASS3 = Class.forName ("Com.tengj.reflect.ReflectDemo");        System.out.println (Class3.getname ());}    }

  

Execution Result:

Com.tengj.reflect.ReflectDemocom.tengj.reflect.ReflectDemocom.tengj.reflect.ReflectDemo

  

Java Reflection-related operations

Before we know how to get the class, what can we do with this class?
Summarized as follows:

    • Get Member Method
    • Get member Variable field
    • Get Constructor constructor

Here's a concrete introduction to

Get Member Method information

Obtaining a method separately is obtained through the following methods of class:

Public method Getdeclaredmethod (String name, Class<?> .... parametertypes)//Get all the methods of the class, excluding the public method of the parent class GetMethod (String name, Class<?> .... parametertypes)//Get all public methods of the class, including the parent class's

  

Two parameters are a list of class types for method names and method parameter classes, respectively.
For example, Class A has one of the following methods:

public void Fun (String name,int age) {    System.out.println ("I Call" +name+ ", this year" +age+ ");}

  

Now that you know that a has an object A, you can go through:

Class C = class.forname ("Com.tengj.reflect.Person");  Mr. Cheng Classobject o = c.newinstance ();                           Newinstance can initialize an instance of method = C.getmethod ("Fun", String.class, Int.class);   Get method Method.invoke (O, "Tengj", ten);                              The method is called by invoke, the first parameter is the instance object, followed by the specific parameter value

  

The complete code is as follows:

public class Person {private String name;private int age;private string msg = "Hello wrold";p ublic String getName () {retur n Name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public person () {}private person (String name) {this.name = name; SYSTEM.OUT.PRINTLN (name);} public void Fun () {System.out.println (' fun ');} public void Fun (String name, int ages) {System.out.println ("I call" + name + ", this year" + Age + "old");}}

public class Reflectdemo {public static void main (string[] args) {try {Class C = class.forname ("Com.tengj.reflect.Person") ; Object o = C.newinstance (); method = C.getmethod ("Fun", String.class, Int.class); Method.invoke (O, "Tengj", 10);} catch (Exception e) {e.printstacktrace ();}}}

Execution Result:

My name Tengj, 10 years old this year.

  

How, is not feeling very bad, we just know this kind of path full name can play with it in the applause between.

Sometimes we want to get information about all the member methods in the class. This can be done in the following steps:

1. Get an array of all methods:

Class C = class.forname ("Com.tengj.reflect.Person"); Method[] methods = C.getdeclaredmethods (); Get all the methods of the class, excluding the parent class or: method[] methods = C.getmethods ();//Get all public methods of the class, including the parent class's

  

2. Then loop through the array to get each method:

for (Method method:methods)

  

The complete code is as follows:
The person class is the same as above, it is not posted here and later, only the key code is affixed

public class Reflectdemo {public    static void Main (string[] args) {        try {            Class C = Class.forName ("COM.TENGJ.R Eflect. Person ");            Method[] methods = C.getdeclaredmethods ();            for (Method m:methods) {                String  methodname= m.getname ();                System.out.println (MethodName);            }        } catch (Exception e) {            e.printstacktrace ();}}    }

  

Execution Result:

Getnamesetnamesetagefunfungetage

  

If the C.getdeclaredmethods () is changed to C.getmethods (), the execution result is as follows, there are many ways to print out the method in object, because object is the parent of all classes:

Getnamesetnamegetagesetagefunfunwaitwaitwaitequalstostringhashcodegetclassnotifynotifyall

  

Get member Variable information

Think about what is included in the member variable: member variable type + member variable name
The member variable of a class is also an object, and it is java.lang.reflect.Field an object, so we java.lang.reflect.Field get the information by encapsulating it inside the method.

Get a member variable separately, implemented by the following methods of the class classes:

Public field Getdeclaredfield (string name)//Gets all of the variables declared by the class itself, excluding the variables of its parent class, public field GetField (string name)// Gets the class from all public member variables, including its parent class variable

  

The parameter is the name of the member variable.
For example, a Class A has the following member variables:

private int n;

  

If a has an object A, then you can get its member variables like this:

Class C = A.getclass (); Field field = C.getdeclaredfield ("n");

  

The complete code is as follows:

public class Reflectdemo {public    static void Main (string[] args) {        try {            Class C = Class.forName ("COM.TENGJ.R Eflect. Person ");            Gets the member variable            field field = C.getdeclaredfield ("msg");//Because the MSG variable is private, you cannot use the GetField method            Object o = c.newinstance ();            Field.setaccessible (TRUE);//Set whether to allow access, because the variable is private, so to manually set allow access, if the MSG is public, you do not need this line.            Object msg = Field.get (o);            SYSTEM.OUT.PRINTLN (msg);        } catch (Exception e) {            e.printstacktrace ();}}    }

  

Execution Result:

Hello Wrold

  

Similarly, if you want to get information about all member variables, you can use the following steps
1. Get an array of all member variables:

field[] fields = C.getdeclaredfields ();

  

2. Iterate through the array of variables to get a member variable field

for (Field Field:fields)

  

Full code:

public class Reflectdemo {public    static void Main (string[] args) {        try {            Class C = Class.forName ("COM.TENGJ.R Eflect. Person ");            field[] fields = C.getdeclaredfields ();            for (Field field:fields) {                System.out.println (Field.getname ())}        } catch (Exception e) {            E.printstacktrace ();}}}    

  

Execution Result:

Nameagemsg

  

Get constructor

And finally think about what is included in the constructor: constructor arguments
As above, the constructor of a class is also an object, and it is java.lang.reflect.Constructor an object, so we java.lang.reflect.Constructor can obtain this information by means of the encapsulated method.

Get a constructor separately, implemented by the following methods of class:

Public constructor<t> getdeclaredconstructor (class<?> ... parametertypes)//  Get all constructors of this class, Constructors that do not include its parent class public constructor<t> getconstructor (class<?> ... parametertypes)//Get the class so the public constructor, including the parent class

  

This parameter is a list of class types for the constructor parameter class.
For example, Class A has one of the following constructors:

Public A (String A, int b) {    //code body}

  

Then you can go through:

Constructor Constructor = A.getdeclaredconstructor (String.class, Int.class);

  

To get this constructor.

Full code:

public class Reflectdemo {public    static void Main (string[] args) {        try {            Class C = Class.forName ("COM.TENGJ.R Eflect. Person ");            Gets the constructor            Constructor Constructor = C.getdeclaredconstructor (string.class);            Constructor.setaccessible (TRUE);//Set whether to allow access, because the constructor is private, so to manually set allow access, if the constructor is public, you do not need this line.            constructor.newinstance ("Tengj");        } catch (Exception e) {            e.printstacktrace ();}}    }

  

Execution Result:

Tengj

  

Note: class's Newinstance method can only be used to create classes that contain only parameterless constructors, and if a class has only constructors with parameters, use another way: Fromclass.getdeclaredconstructor ( String.class). newinstance ("Tengj");

To get all the constructors, you can do this by following these steps:
1. Get all the constructors for the class and put them in an array:

Constructor[] Constructors = c.getdeclaredconstructors ();

  

2. Iterate through the array of constructors to get a constructor constructor:

for (Constructor constructor:constructors)

  

Full code:

public class Reflectdemo {public    static void Main (string[] args) {            constructor[] constructors = C.getdeclaredconstructors ();            for (Constructor constructor:constructors) {                System.out.println (Constructor);            }        } catch (Exception e) {            e.printstacktrace ();}}}    

  

Execution Result:

Public Com.tengj.reflect.Person () public Com.tengj.reflect.Person (java.lang.String)

  

Understanding the nature of set generics through reflection

The first conclusion is:

Generics in Java are protected from erroneous input and are valid only during the compilation phase, bypassing compilation to run time.

The following is an example to verify:

/** * Collection Generics Nature * @description * @author Trigl * @date April 2, 2016 morning 2:54:11 */public class Genericessence {public static V OID Main (string[] args) {List list1 = new ArrayList ();//no generic list<string> list2 = new Arraylist&lt ; String> (); There is a generic/* * 1. First observe the normal way of adding elements, in the compiler check generics, * This time if list2 add int type will error */list2.add ("Hello"); /List2.add (20); Error! List2 has a generic limit, can only add string, add int error System.out.println ("List2 length is:" + list2.size ()); At this point the List2 length is 1/* 2. Then add elements by reflection, dynamically load classes at run time, first get the same class type as List1 and List2 *, and then call the Add method with the method reflection bypass the compiler to see if I can be inserted        NT * Type Element */Class C1 = List1.getclass ();        Class C2 = List2.getclass (); SYSTEM.OUT.PRINTLN (C1 = = C2);  Result: true, stating that the class type is exactly the same//validation: We can add elements to list2 through the reflection of the method, so that we can bypass the compile check try {Method m = C2.getmethod ("Add", Object.class); The Add Method M.invoke (List2, 20) is obtained by reflection of the method. Add an int to List2, which shows that the compiler will give an error SYSTEM.OUT.PRINtln ("The length of the List2 is:" + list2.size ());        Results: 2, indicating list2 length increased, and no generic check} catch (Exception e) {e.printstacktrace ();         As you can see in the compiler, generics restrict the consistency of element types within the collection, but after the compiler finishes entering the * run time, generics no longer work, and even elements of different types can be inserted into the collection. */    }}

  

Execution Result:

The length of the List2 is: the length of the 1truelist2 is: 2

  

Summarize

To this, the Java reflection mechanism to get started almost, I was reviewing SPRINGMVC inside Ioc/di, the underlying principle is through the Java reflection to achieve, I hope this note also useful for you.

Reference

In-depth explanation of the Java reflection mechanism
Getting Started with Java reflection
Java Reflection mechanism
Java Reflection detailed
A brief analysis of Java reflection mechanism
Understanding of reflection mechanism and its use

Mind map for finishing

Personal grooming of the Java reflection mechanism of mind map, exported pictures can not view some information about notes, so the need for the source of children's shoes can focus on my profile on the public number, reply to the reflection mechanism to get the source files.


Always feel that they are not writing technology, but feelings, an article is their own traces of this way. Rely on the success of professional skills is the most replicable, I hope this road can let you less detours, I hope I can help you erase the knowledge of the dust, I hope I can help you clear the context of knowledge, I hope that the future of technology on the top of you also have me.

Original address: HTTP://WWW.JIANSHU.COM/P/1A60D55A94CD

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.