On the reflection mechanism of Java

Source: Internet
Author: User

Recently and a senior exchange of Java, really is a great harvest, let me learn a little Javad reflection mechanism, and finally understand the spring and other framework of a basic realization of the idea, then today and you share the Java reflection mechanism.

Reflection, reflection, listen to his name just like in the mirror, you can see that you can see every part of others. This is a very important feature in the Java language. The following is a description of the reflection from Sun's website:

Reflection is a feature in the Java programming language. It allows a executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the prog Ram. For example, it's possible for a Java class to obtain the names of the and display them.

The ability to examine and manipulate a Java class from within itself could not be sound like very much Ng languages This feature simply doesn ' t exist. For example, there is no-in-a-a-Pascal, C, or C + + program-to-obtain information about the functions defined within Program.

One tangible use of reflection are in JavaBeans and where software components can manipulated visually via a builder tool. The tool uses reflection to obtain the properties of Java components (classes) as they is dynamically loaded.

So the explanation is that reflection is a feature of the Java language that allows programs to self-check and manipulate internal members at runtime (note that it is not a compile time). For example, it allows a Java class to fetch all of his member variables and methods and display them. This can be specific to us, but it does not exist in other languages such as C or C + +. A common example is in JavaBean, where some components can be manipulated by a constructor. This constructor is used to get the properties of the class in Java when the reflection is loaded dynamically.

Pre-Transmission of reflection: Class-Type class class

There is a class in Java that is special, that is, class, A lot of friends in the writing process, such as apple.class to look at the type information, you can understand it as encapsulating the information of the class, many explained that class does not have a constructor, in fact, there is, but its construction method is private (constructor and private??). Yes, this is to prohibit developers from creating instances of class classes themselves. We can look at the source code in the JDK:

The note clearly tells us that this class is created with a JVM, so we don't have to bother. If we get the type information of a class, we can use reflection to get its various members and methods. (Note: Class started more as a generic service since the JDK1.5 version) so how do we get a type of information? Suppose we have a role class:

1package Yui;
2
3/**
4 * A base class Having some attributes and methods
5 * @author Octobershiner
6 * @since 2012 3 17
7 *
8 * * *
10publicclass Role {
11
12private String name;
13private String type;
14
15//Constructors
16public Role () {
System.out.println ("Constructor Role () is invoking");
18}
19//Private Builder
20private Role (String name) {
21this.name = name;
System.out.println ("Constructor Role (String name) is invoking.");
23}
24
25//get and Set method
26
27public String GetName () {
28return name;
29}
30publicvoid setName (String name) {
31this.name = name;
32}
33public String GetType () {
34return type;
35}
36publicvoid setType (String type) {
37this.type = type;
38}
39
40//override the ToString method to show the class
@Override
42public String toString () {
43return "This is a role called" +THIS.NAME;
44}
45
46}

There are two main ways to do this without an object instance.

Two ways to get class types
Class cls1 = Role.class;
Class cls2 = Class.forName ("Yui. Role ");

Note In the second way, the parameters in forname must be the complete class name (package name + class name), and this method needs to catch the exception. Now that you get CLS1, you can create an instance of the role class, using the class's Newinstance method as the default constructor for calling classes.

        Object o = cls1.newinstance (); Create an instance
Object O1 = new Role (); Equivalent to the above method

This creates an object, and the disadvantage is that we can only take advantage of the default constructor, because the newinstance of class does not accept arguments, and then the newinstance of acceptable parameters, and second, if the constructor of a class is private, such as class, We still cannot instantiate its object.

Gets the constructor for the class

First introduce the constructor class, which encapsulates the reflected constructor, class has four ways to get the constructor object

    • Public constructor< >[] GetConstructors () returns all the public constructor collections in the class, with the default constructor subscript 0
    • Public constructor< a href= "http://www.cnblogs.com/octobershiner/admin/" title= "type parameter in Class" Style= ' Font-size:13px;font-style:normal;font-weight:700;color:rgb (0, 102, 204); ' >T</a>< GetConstructor (Class <. Parametertypes) returns the specified public constructor, which is a collection of constructor parameter types
    • Public constructor< >[] Getdeclaredconstructors () returns all constructors in the class, including private
    • Public constructor< a href= "http://www.cnblogs.com/octobershiner/admin/" title= "type parameter in Class" Style= ' Font-size:13px;font-style:normal;font-weight:700;color:rgb (0, 102, 204); ' >T</a>< Getdeclaredconstructor (class<; parametertypes) returns any specified constructor
From the name point of view, it is still very understood, with declared is to get all the construction methods, including private, ha, we can call the original is not allowed to call the private constructor, see the code
1/**
2 * Get Construction method constructor
3 * GetConstructor ()
4 * Getdeclaredconstructor ()
5
6 * * *
7
8//specifying a parameter list for a specific method
9 Constructor con = cls1.getdeclaredconstructor (new Class[]{string.class});
con.setaccessible (TRUE);//Set accessible permissions
One Object obj = con.newinstance (new object[]{"Liyang"});
System.out.println (obj); Print the information for this object
13
14//get all the constructor method collections
Constructor con1[] = cls1.getdeclaredconstructors ();
con1[1].setaccessible (TRUE);
obj1 Object = con1[1].newinstance (new object[]{"Tom"});
System.out.println (OBJ1);
  To explain: The first is to get a specified method, we specify that the parameter is a string type, the second paragraph we get all the constructor method collection, and select one of them to create a new object.  Note that the constructor Newinstance method here can set the parameters, and the same method in front of the article to form a comparison. Note that the above four methods all need to throw an exception, when we get a private method, to use Setaccessible to set the access permissions, the example does not demonstrate the acquisition of common methods, the relatively simple, do not introduce, actually mastered the above two, the other is good understanding.   Get member variables for class                               &N Bsp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                            to understand the constructor, you can guess how to get the member variable, Member variables are encapsulated with the field class.         The main methods are very similar:
    • Public Field Getdeclaredfield (String name) gets the member of any specified name
    • Public field[] Getdeclaredfields () gets all the member variables
    • Public Field GetField (String name) gets an arbitrary public member variable
    • Public field[] GetFields () gets all the public member variables
You can see that these methods are similar, okay, just take a look at the example.
1/**
2 * Get member Variable field
3 * GetField ()
4 * Getdeclaredfield ()
5 * * *
6 Field mem = Cls1.getdeclaredfield ("name");
7 mem.setaccessible (TRUE);
8 System.out.println ("We get form field:" +mem.get (obj));
9
  This is the access to private variables, what private variables can also be accessed?? Yes....   Get class methods                               &NBS P                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                            I think you can help me write this paragraph, the method of encapsulation class Class is method. There are four ways to get the method, guessed it?
    • Public method[] GetMethods () Gets the collection of all common methods
    • Public method GetMethod (String name,class<, ... parametertypes) gets the specified publicly-available methods parameter 1: Method name parameter 2: Parameter type collection
    • Public method[] Getdeclaredmethods () get all the methods
    • Public method Getdeclaredmethod (String name,class<, ... parametertypes) gets any of the specified methods
Look at the following example.
1/**
2 * Method of calling Class
3 * GetMethod ()
4 * Getdeclaredmethod ()
5
6 * * *
7 Method f = Cls1.getmethod ("GetName", null);
8 Object name = F.invoke (obj, null);
9 System.out.println ("We Invoke method:" + name);
  This is simple, we just have to pass NULL when we have no argument.   Summary:                                                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp               The above is the simple use of the reflection mechanism, obviously the friends who have learned spring must understand, why we can get the specified methods and variables through the configuration file. When we create the object, it is done by passing in a string, just like what you need, we are going to produce for you, and we are always using object, which means that the dynamic nature of the Java language, the dependency greatly reduced.  
Full Source code in this article address:https://github.com/octobershiner/Java-Taste/tree/master/Reflection Please support Java Taste project:https://github.com/octobershiner/Java-Taste

On the reflection mechanism of Java

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.