Java reflection and java reflection

Source: Internet
Author: User

Java reflection and java reflection
I. Concepts

In one sentence, reflection "reflection is to map various components in the Java class into corresponding Java classes ". If you have a good understanding of reflection, I believe you will have a lot of resonance with this sentence.

In other words, each member of a Class can be expressed by an instance object of the corresponding reflection API Class (for example), by calling the Class method (getField, getMethod, getConstructor, etc) you can obtain these instance objects.


  


That is to say, a Java Class is represented by a Class object. The components of a Class: member variables, methods, constructor methods, packages, and other information are also represented by Java classes. Just like a car is a class, the engine and gearbox in a car are also a class. Indicates the Class of the Java Class. It is clear that a series of methods are required to obtain the variables, methods, constructor, modifier, package, and other information, the information is represented by the instance objects of the corresponding class. They are Field, Method, Contructor, Package, and so on.

2. Understand the Class

Each Java Class in a Java program belongs to the same class. The Java Class name that describes this class is Class (note the difference between lower-case classes ).

For example, for the Person Class representative, its instance objects are specific persons such as "Zhang San" and "Li Si". Similarly, the Class represents the Java Class, its Instance Object corresponds to the bytecode of each class in the memory, such as the Person class bytecode and the ArrayList class bytecode.

Three methods to obtain bytecode (Class type) are as follows:


  


To understand the concept of bytecode:


  


Iii. Common Reflection applications

Next we will briefly introduce the reflection applications of constructor, member variables, and member methods:

3.1 Constructor class reflection application of Constructor)

The Contructor class represents a constructor in a class.

Obtain all the constructor methods of a class:

Example: Contructor [] constructors = Class. forName ("java. lang. String"). getConstructors ();

Obtain a constructor of a class:

Example: Contructor [] constructors = Class. forName ("java. lang. String"). getConstructors (StringBuffer. class );

The sample code is as follows:

Package com. tgb. constructorReflect; import java. lang. reflect. constructor; public class TestConstructorReflect {public static void main (String [] args) throws Exception {// 1, General (non-reflection) string str1 = new String (new StringBuffer ("zhipeng"); // 2. Reflection Constructor <String> constructor = String. class. getConstructor (StringBuffer. class); String str2 = (String) constructor. newInstance (new StringBuffer ("zhipeng "));}}

A class has multiple constructor methods. How can we identify which method we want to obtain? Based on the number and type of parameters, for example, CIass. getMethod (name, CIass... The args parameter in args) represents a list of the types of parameters of the method to be obtained. Key: How does one express the parameter type? Class instance object. For example, int. Class, int []. Class, etc.

The Class. newInstance () method first obtains the byte code of the default constructor object of the Class, and then uses it to create an instance object.

3.2 reflection application of member variables (Field Class)

The Field class represents the member variables in a class.

Sample Code 1 is as follows:

First define a ReflectPoint class

Public class ReflectPoint {private int x; // note that x is a private public int y; public ReflectPoint (int x, int y) {super (); this. x = x; this. y = y ;}}

Then we first get the bytecode of the ReflectPoint class, and then take out the bytecode of a certain attribute of it, and then we can get the corresponding attribute values of any object in this class:

Import java. lang. reflect. field; public class TestFieldReflect {/*** author: zhipeng */public static void main (String [] args) throws Exception {ReflectPoint pt1 = new ReflectPoint (1, 2 ); reflectPoint pt2 = new ReflectPoint (10, 12); Field fieldY = ReflectPoint. class. getField ("y"); // get the ReflectPoint [Class] is the definition of the property name y (bytecode) System. out. println ("pt1 ---> y --->" + fieldY. get (pt1); // output object pt1 property y: 2System. out. println ("pt2 ---> y --->" + fieldY. get (pt2); // property of the output object pt2 y: 12 Field fieldX = ReflectPoint. class. getDeclaredField ("x"); // If x is private, use getDeclaredFieldfieldX. setAccessible (true); // brute force reflection System. out. println (fieldX. get (pt1); // property of the output object pt1 x: 1 }}

Above we use [FieldfieldY = ReflectPoint. class. getField ("y");] Does the obtained Field object correspond to the member variables on the class or the member variables on the object? In our analysis, there is only one class, and there are multiple instance objects of the class. If it is associated with the object, which object is associated? Therefore, fieldX represents the definition of x, rather than the specific x variable. That is to say, we get the corresponding definition (bytecode) of x in ReflectPoint. class, and use it to get the attribute values corresponding to an instance object.

Sample Code 2 is as follows:

First define a Student class

/*** @ Author wangzhipeng */public class Student {// 1. Define two Fieldpublic String userName; public String password; // 2. constructor, assign public Student (String username, String password) {this. userName = username; this. password = password;} // 3. Rewrite its toString method @ Overridepublic String toString () {return "username:" + this. userName + "Password:" + this. password ;}}

Then, we use reflection to change the letter "a" in the attribute value of any Student object to "[B]". The Code is as follows:

Import java. lang. reflect. field; public class TestChangeStringValue {public static void main (String [] args) throws IllegalArgumentException, IllegalAccessException {Student zhipeng = new Student ("akdent", "a123"); System. out. println (zhipeng); // before modifying attributes, output: Username: ak133 password: a123ChangeStrValue (zhipeng); // call the method System for changing attributes. out. println (zhipeng); // After modifying the attributes, output: Username: [B] kobe password: [B] 123} public static void ChangeStrValue (Object object Object) throws IllegalArgumentException, illegalAccessException {// 1. Obtain all attributes of the class Field [] fields = object through reflection. getClass (). getDeclaredFields (); // 2. loop variable attributes. If the attribute type is String, change the letter "a" in the attribute to "[B]" for (Field field Field: fields) {if (field. getType () = String. class) {String oldValue = (String) field. get (object); String newValue = oldValue. replace ("a", "[B]"); field. set (object, newValue );}}}}

3.3 reflection application of member methods (Method class)

The Method class represents a member Method in a class.


  


Sample Code 1 is as follows:

First, define a Student class with a static method and a non-static method:

/*** @ Author wangzhipeng */public class Student {// 1. Define a static Method Study () public static void Study () {System. out. println ("static method ---> Study ()");} // 2. Define a non-static method (String songName) public void Sing (String songName) {System. out. println ("not static method ---> Sing ():" + songName );}}

Then we execute these two methods in reflection and pay attention to their differences:

Import java. lang. reflect. method; public class MethodReflectTest {public static void main (String [] args) throws Exception {// 0, get Student's classClass clazz = Student. class; // 1. The [non-static] Method of the Student class is reflected and executed: Sing (String songName) Method methodSing = clazz. getMethod ("Sing", String. class); // The second parameter is the [type] methodSing of the parameter. invoke (new Student (), "Ice Rain"); // a non-static method belongs to an object, so the first parameter is a Student object. // 2. Execute the [static] Method of the Student Class: static void Study () Method methodStudy = clazz. getMethod ("Study", null); methodStudy. invoke (null, null); // The static method belongs to the class, so the first parameter is null. This method does not have a parameter, so the second method is null }}

Sample Code 2 is as follows:

We use reflection to execute a class of main methods.

First define a Teacher class:

Public class Teacher {// defines the static main method public static void main (String [] args) {for (String arg: args) {System. out. println (arg );}}}

Then we write a tool class and execute the main method of any class:

// Tool Class: Execute the main Method public static void ExecuteMainMehod (Class clazz, String [] argStrings) throws Exception {Method teacherMainMethod = clazz. getMethod ("main", String []. class); // teacherMainMethod. invoke (null, new String [] {"aaa", "bbb" //}); // reports wrong number of arguments (that is, the number of parameters is abnormal) teacherMainMethod. invoke (null, new Object [] {argStrings}); // you need to input the argStrings package layer by layer, because jdk1.4 will unpack this parameter by default}

Test and run the main method of the Teacher class:

Public static void main (String [] args) throws Exception {String [] argStrings = new String [] {"aaa", "bbb"}; ExecuteMainMehod (Teacher. class, argStrings); // output: aaa // bbb}


Iv. Purpose

Reflection is available from java1.2. Its biggest purpose should be to write the framework. Why? First, we need to understand that the framework (such as Spring) is actually calling our class. However, the framework has been written, but the called (our) class has not yet been written, which is somewhat different from our sequential thinking. The reason why the framework can call a class that does not exist is that it cannot be reflected.

When your class has not been written, I can call it, as long as you write it out during the runtime. This is what reflection does. For example, Spring:


  


Similar to the above spring configuration, We need to configure the class name [attribute name] and so on in all the framework configuration files. You don't have to think about it for reflection.


V. Summary

Reflection maps various components in the Java class into corresponding Java classes. For example, it maps Constructor classes to Constructor classes, Field classes to attributes, and methods to Method classes.

The biggest purpose of reflection we have come to is to write the framework. We need to configure the class name and attribute name of our business class in the configuration files of Spring, Struts, and other frameworks, this is to reflect its objects, attribute values, methods, and so on at runtime. Because the Framework calls the non-existent business classes that we have not yet written, it cannot be separated from reflection.

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.