In this paper, the Java Reflection mechanism is analyzed in detail. Share to everyone for your reference, specific as follows:
First, pre-needed knowledge (Java Virtual machine)
Method area for Java virtual machines:
Java Virtual machine has a Run-time data area, this data area is divided into method area, heap area and stack area, we need to understand here is mainly the method area. The primary function of the method area is to store the type information of the loaded class, when a Java virtual machine loads a type, the class loader needs to locate the corresponding class file and then read it into the Java virtual machine, and then the virtual machine extracts the type information from class and stores the information in the method area. This information mainly includes:
1, this type of fully qualified name
2, the fully qualified name of this type of direct super class
3, whether this type is a class type or an interface type
4, this type of access modifier
5. Ordered list of fully qualified names of any direct Super interface
6, the type of constant pool
7. Field Information
8. Method information
9. All class variables except constants
10, a reference to class classes
And so on (the reader can refer to the narrative in the Deep Java Virtual machine book)
Class classes:
Class class is a very important Java base class, and whenever a new type is loaded, the Java Virtual machine creates a class instance in the Java heap that corresponds to the new type, which represents this type, through which we can access the basic information of that type. It says that the type information of a loaded class is stored in the method area and we can access that information through the class instance. For example, there are corresponding methods for the information class mentioned above, as follows:
1, GetName (); Fully qualified name of this type
2, Getsuperclass (); The fully qualified name of this type of direct super class
3, Isinterface (); Is this type a class type or an interface type?
4, Gettypeparamters (); This type of access modifier
5, Getinterfaces (); an ordered list of fully qualified names of any direct hyper-interfaces
6, GetFields (); Field information
7, GetMethods (); Method information
Et cetera (readers can see the JDK help document for more information themselves)
Second, Java reflection detailed
The notion of reflection: the so-called reflection is the ability of the Java language to have a view of itself at runtime, reflection enables your program code to get internal information about the classes that are loaded into the JVM, allowing you to execute the program to get internal information about the class, rather than having to know the internal information of the required class while writing the code. This makes reflection a major tool for building flexible applications.
Common classes and functions of reflection: The Java Reflection mechanism is implemented with the help of 4 classes: Class,constructor,field,method; where class represents the class object, the constructor object of the Constructor-class, the Property object of the Field-class, The method object of the Method-class, through which we can roughly see the various components of a class. The core of which is the class classes, it is the basis for reflection, it contains methods we have in the first part of the basic elaboration. The most important thing we care about when applying reflection is a class constructor, a property, and a method, and here we introduce the methods for these three elements in class classes:
1, get the constructor method
Constructor GetConstructor (class[] params)--Gets a public constructor that uses a particular parameter type.
Constructor[] GetConstructors ()--get all public constructors for a class
Constructor Getdeclaredconstructor (class[] params)--get a constructor that uses a specific parameter type (regardless of the access level)
Constructor[] Getdeclaredconstructors ()--gets all constructors of the class (regardless of access level)
2, the method of obtaining the field information
Field GetField (String name)--Get a named public field
Field[] GetFields ()--Get all public fields of a class
Field Getdeclaredfield (String name)--Gets the named field declared by the class
Field[] Getdeclaredfields ()--Get all the fields declared by the class
3. Methods of obtaining method information
Method GetMethod (String name, class[] params)--use a specific parameter type to get the named public methods
Method[] GetMethods ()--Get all the public methods of a class
Method Getdeclaredmethod (String name, class[] params)--Methods for naming a class declaration using the parameter type of a feature
Method[] Getdeclaredmethods ()--all methods of obtaining a class declaration
Basic steps for applying reflection:
1, get the class object that you want to operate;
Method One: Classc=class.forname ("java.lang.String")///This way the class object for the classes requires a package name. Class Name
Method Two: For basic data types you can use statements that form class C=int.class or class C=integer.type
Method Three: Class C=myclass.class
2. Call the method in class to get the set of information you want to get, such as calling the Getdeclaredfields () method to get all the attributes of the class;
3, processing the information obtained in the 2nd step, and then do what you want to do the actual operation.
Reflection instances:
Now I'll give you three examples of class constructors, properties, and methods to illustrate the application process of reflection.
1. Construction Device
The step is: to get the constructor of a class from the reflection mechanism, and then call the constructor to create an instance of the class
Import java.lang.reflect.*;
public class constructordemo{public
Constructordemo () {} public
Constructordemo (int a, int b) {
System.out.println ("a=" +a+ "b=" +b);
}
public static void Main (String args[]) {
try {
Class cls =class.forname ("package name.") Constructordemo ");
Class partypes[] =new class[2]; Partypes[0] = Integer.type;
Partypes[1] =integer.type;
Constructor Ct=cls.getconstructor (partypes);
Object arglist[] =new object[2];
Arglist[0] = Newinteger (Panax notoginseng);
ARGLIST[1] = Newinteger (a);
Object retobj = ct.newinstance (arglist);
} catch (Throwable e) {
System.err.println (e);}}}
2, properties
The step is to get a property of a class from the reflection mechanism and then change the property value corresponding to an instance of the class
Import java.lang.reflect.*;
public class fielddemo1{public
double D;
public static void Main (String args[]) {
try {
Class cls = Class.forName ("FieldDemo1");
Field fld = Cls.getfield ("D");
FieldDemo1 fobj = new FieldDemo1 ();
System.out.println ("D =" + FOBJ.D);
Fld.setdouble (Fobj, 12.34);
System.out.println ("D =" + FOBJ.D);
} catch (Throwable e) {
System.err.println (e);}}}
3. Methods
The procedure is to get a method of a class through the reflection mechanism, and then call the method corresponding to an instance of the class
Invokes the method by using the name of the method
import java.lang.reflect.*;
public class methoddemo1{Public
int Add (int a, int b) {return
a + b;
}
public static void Main (String args[]) {
try {
Class cls =class.forname ("MethodDemo1");
Class partypes[] = new class[2];
Partypes[0] = Integer.type;
PARTYPES[1] = Integer.type;
Method meth = Cls.getmethod ("Add", partypes);
MethodDemo1 methobj = new MethodDemo1 ();
Object arglist[] = new object[2];
Arglist[0] = new Integer (Panax Notoginseng);
ARGLIST[1] = new Integer (a);
Object retobj= Meth.invoke (methobj, arglist);
Integer retval = (integer) retobj;
System.out.println (Retval.intvalue ());
} catch (Throwable e) {
System.err.println (e);
}
}
}
Third, Java Reflection Application (Hibernate)
We have a comparison of Java reflection in the second part of the system, but also to give a few simple examples, we will discuss the specific application of Java reflection. As we already know, the Java reflection mechanism provides a versatile method for dynamically linked program components that allow programs to create and control objects of any class (based on security restrictions) without having to hard-code the target class ahead of time. These features make reflection particularly useful for creating libraries that collaborate with objects in a very common way. For example, reflection is often used in a framework that continuously stores objects as databases, XML, or other external formats. Here we have hibernate the framework as an example to illustrate the significance of reflection.
Hibernate is a masking jdbc, an ORM Java framework that enables us to discard tedious SQL statements and instead use the Save () method of the session class in hibernate to directly save objects of a class to the database. That is, the code involved in the SQL statement hibernate helped us do it. Then there was a problem, hibernate how do you know what attributes of an object he was saving? What are the types of these attributes? So, how does it construct the SQL statement when it stores the object's properties in the database? The tool to solve this problem is our Java reflection!
Here's an example of how we define a user class that has 20 properties and the get and set methods of these properties, and the corresponding user table in the database, with 20 fields in the user table. Suppose we extract a record from the user table, we now need to assign the contents of the 20 fields of this record to the 20 attributes of the user object MyUser, and the hibernate framework does not know the user class at compile time, He could not directly call the Myuser.getxxx or Myuser.setxxx method, the reflection is used at this time, the specific processing process is as follows:
1, according to query conditions to construct the Preparedstament statement, the statement returns the value of 20 fields;
2, hibernate by reading the configuration file to get the user class list of attributes (is a string array) and the types of these properties;
3, create the class object of MyUser belongs to C;c=myuser.getclass ();
4. Construct A For loop, and the number of loops is the length of the list;
4.1, read the value of List[i], and then construct the set method of the attribute;
4.2, judge the type of list[i] xxx, call the preparedstament statement of the GETXXX (i), and then get the value of I out of the field;
4.3, the value obtained in 4.2 as 4.1 of the Set method parameters, so that the completion of a field like an attribute of the assignment, so the cycle can be;
See, this is the reflection of the credit, if there is no reflection it is difficult to imagine if the completion of the same function will be how difficult! But reflection also has shortcomings, such as low performance, security is more complex, etc., here is not to discuss these things, interested readers can find the answer online, there are a lot of!
I hope this article will help you with Java programming.