Go The use of java-reflection mechanism

Source: Internet
Author: User

Implementation principle of Java reflection mechanism


Reflection mechanism: The so-called reflection mechanism is the ability of the Java language to have a self-view at runtime. This ability allows you to thoroughly understand your situation and prepare for the next move. The following is a detailed description of the Java reflection mechanism. Here you will subvert the original understanding of Java.

The implementation of the reflection mechanism in Java is based on 4 classes: Class,constructor,field,method, which class represents the time class object, the constructor object of the Constructor-class, the Property object of the Field-class, The method object for the Method-class. With these four objects we can roughly see the various components of a class.

Class: When the program runs, the Java runtime system handles all objects at run-time types. This information records the classes that each object belongs to, and the virtual machine typically chooses the correct method to execute using the run-time type information (excerpt from: White Paper). But how do we get this information, we need to use the class object Ah. The GetClass () method is defined in the object class. We can get the class object of the specified object through this method.

The Java reflection mechanism mainly provides the following features:

1. At run time, determine the class to which any one object belongs.

2. Constructs an object of any class at run time.

3. At run time, judge the member variables and methods that any one class has.

4. A method that invokes any object at run time.

Reflection is a key property of Java as a dynamic (or quasi-dynamic) language.

This mechanism allows the program to obtain the internal information of any given class with a known name through the reflection APIs at runtime.

Includes all information about its modifiers (such as public, static, and so on), superclass (such as object), interfaces implemented (such as Serializable), and its fields and methods. You can change the fields content or call methods at run time.

Then we can get the information we need by analyzing the object.

For example: ArrayList ArrayList;

Class clazz = Arraylist.getclass ();

Then I'll deal with this object clazz.

Of course, the class has a lot of methods, and the emphasis here is on the methods that are related to the Constructor,field,method class.

Reflection is one of the characteristics of the Java programming language, which allows the running Java program to check itself, or "self-audit", and to directly manipulate the internal properties of the program. Java's ability in practice may not be used in many, but the individual think to have a more in-depth understanding of Java should be mastered.

1. Detection class:

The working mechanism of reflection

Consider the following simple example, let's see how reflection works.

Import Java.lang.reflect.Method;

public class Dumpmethods {

public static void Main (String args[]) {

try {

Class C = class.forname (Args[0]);

Method m[] = C.getdeclaredmethods ();

for (int i = 0; i < m.length; i++)

System.out.println (M[i].tostring ());

} catch (Throwable e) {

System.err.println (e);

}

}

}



EXECUTE as follows:

Java dumpmethods java.util.ArrayList

This program uses Class.forName to load the specified class, and then calls Getdeclaredmethods to get a list of the methods defined in the class. Java.lang.reflect.Methods is a class used to describe a single method in a class.

main methods in Java class reflection

For any of the following three categories of components-constructors, fields, and methods-Java.lang.Class provides four separate reflection calls to obtain information in different ways. Calls follow a standard format. The following is a set of reflection calls used to find a constructor:

Constructor GetConstructor (class[] params)--get a public constructor that uses a special parameter type,

Constructor[] GetConstructors ()--get all public constructors for the class

Constructor getdeclaredconstructor (class[] params)--get constructors with specific parameter types (independent of access level)

Constructor[] Getdeclaredconstructors ()--Get all constructors for class (independent of Access level)

The class reflection call that obtains the field information differs from those used to access the constructor, using the field name in the parameter type array:

Field GetField (String name)--Get the named public field

Field[] GetFields ()--Get all the public fields of the class

Field Getdeclaredfield (String name)--The named field that gets the class declaration

Field[] Getdeclaredfields ()--Get all the fields declared by the class

used to obtain method information functions:

Method GetMethod (String name, class[] params)--use a specific parameter type to get a named public method

Method[] GetMethods ()--get all public methods of the class

Method Getdeclaredmethod (String name, class[] params)--use the close-up parameter type to get the name of the class declaration

Method[] Getdeclaredmethods ()--all methods of obtaining class declarations

using Reflection:

Classes for reflection, such as Method, can be found in the Java.lang.relfect package. There are three steps to follow when using these classes: The first step is to get the Java.lang.Class object of the class you want to manipulate. In a running Java program, use the Java.lang.Class class to describe classes and interfaces, and so on.

here is one way to get a Class object:

Class C = class.forname ("java.lang.String");

This statement gets the class object of a String class. There is another way, such as the following statement:

Class C = int.class; or Class C = integer.type;

They can obtain basic types of class information. The latter method accesses the pre-defined type field in the underlying type's encapsulated class (such as Intege).

The second step is to call a method such as Getdeclaredmethods to get a list of all the methods defined in the class.

Once this information is available, a third step can be made-using the reflection API to manipulate this information, as in the following code:

Class C = class.forname ("java.lang.String");

Method m[] = C.getdeclaredmethods ();

System.out.println (M[0].tostring ());

It will print the prototype of the first method defined in String as text.

Working with objects:

A. Creating a Class object
B. Creating a Field object from GetField
C. Call the Field.getxxx (object) method (XXX is int,float, etc., if the object is omitted; object refers to an instance).

For example:

Import java.lang.reflect.*;

Import java.awt.*;

public class Sampleget {

public static void Main (string[] args) {

Rectangle r = new Rectangle (100, 325);

Printheight (R);

}

static void Printheight (Rectangle r) {

Field Heightfield;

Integer Heightvalue;

Class C = R.getclass ();

try {

Heightfield = C.getfield ("height");

Heightvalue = (Integer) heightfield.get (R);

System.out.println ("Height:" + heightvalue.tostring ());

} catch (Nosuchfieldexception e) {

System.out.println (e);

} catch (SecurityException e) {

System.out.println (e);

} catch (Illegalaccessexception e) {

System.out.println (e);

}

}

}

Build Object

1. Obtain the class object first, and then generate it directly from the Newinstance () method of the Class object:

class<?> ClassType = String.class; Object obj = classtype.newinstance ();

2. First obtain the class object, then obtain the corresponding constructor object through the object, and then through the constructor object's Newinstance () method generation (where customer is a custom class, there is a parameterless construction method, There are also construction methods with parameters):

class<?> ClassType = Customer.class;

Gets the constructor object, where the first parameterless construction method is obtained.

Constructor cons = Classtype.getconstructor (new class[] {});

To build an object by constructing a method

Object obj = cons.newinstance (new object[] {});

3. If you want to generate an object from a class's constructor with parameters, you can only use one of the following methods:

(Customer is a custom class with a constructor with no arguments, and a constructor with parameters, passing in strings and integers)

class<?> ClassType = Customer.class;    Constructor cons2 = Classtype.getconstructor (new class[] {string.class, int.class}); Object obj2 = cons2.newinstance (new object[] {"Zhangsan", 20});

You can see that calling the constructor method to build the object is similar to calling a generic method, unlike getting a constructor object from a class object without specifying a name, and getting the method object with a name

Go The use of java-reflection mechanism

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.