Recent study found in many areas, the basic knowledge is still very weak, so for the structure, knowledge points, etc. belong to the kind of ask what what know, do what not come out of that type. Some days ago, the teacher has been grasping the foundation, do everything to start from the simplest demo, only understand the principle and then to use some advanced things such as the framework will understand more profound. The first thing to understand now is the reflection technology that is basically used in every Java framework.
To understand reflection, you first need to understand the loading process of the class, look at the following figure:
Our source code is compiled into bytecode, and then, when run in the JVM, the byte code is generated in memory by loading the bytecode into the class object, which contains the Field object (the class's member variable is generated), The constructor object (the constructor of the class is generated) and method objects (methods of the class are generated). When we get a class or object, we can manipulate them by reflection, and then look at the reflection:
What is reflection Java reflection is primarily the ability of a program to access, detect, and modify its own state or behavior, a key property of a dynamic (or quasi dynamic) language that Java is considered to be. This mechanism allows the program to obtain internal information, including its modifiers (such as public, static, and so on), superclass (such as Object), in any class of a known name through the reflection APIs at run time, Implementation interfaces (such as cloneable), also includes all information about fields and methods, and can change fields content or evoke methods at run time. The Java reflection mechanism allows a program to load, detect, and use a classes that is completely unknown during compilation. In other words, Java can load a runtime to know the name of class, get its complete structure.
Where is the reflection used for frameworks and components, write a general-purpose program with high reusability. such as struts form, as long as the form object and property name can be reflected to the property assignment and value to this kind of operation A method can be done. If Hibernate does not use a field for reflection mapping then each HQL compilation and result processing will not be able to do so. How to use the different situations we know to get the class byte code object in 3 ways. When a class name is known, it is obtained by "object. GetClass" When a known object is acquired by "class name. Class". When the full class name, including the package name, is known (assumed to be string format), the object instance can be constructed, the Property object, the method object, and the constructor object in the object are obtained by using "Class.forName (String)" To get the class byte code object. After getting the various objects that you need, you can manipulate them, and then do the operations of adding and checking. Pros and cons are what advantages Why to use the reflex mechanism. Do you want to create an object directly? This involves the concept of dynamic and static, static compilation: The type is determined at compile time, the binding object is passed. Dynamic compilation: The runtime determines the type, binding the object. Dynamic compilation maximizes the flexibility of Java and embodies the application of polymorphism to reduce the coupling between classes. in one word, the advantage of reflection mechanism is that it can achieve dynamic creation of objects and compile, showing great flexibility, especially in the development of Java EE its flexibility on the performance is very obvious. For example, a large software, it is not possible to put it in a perfect design, when the program compiled, released, when the discovery needs to update some features, we can not have the user to the previous uninstall, and then reinstall the new version, if so, this software is certainly not how many people use. Static, you need to recompile the entire program to achieve the function of the update, and the use of reflection mechanism, it can not uninstall, only to be dynamic in the runtime to create and compile, you can achieve this function. Disadvantage Its disadvantage is that it has an impact on performance。 Using reflection is basically an interpretation operation, we can tell the JVM what we want to do and it meets our requirements. Such operations are always slower than performing the same operations directly. Examples
method to get the class byte code object
<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:14PX;" >/**
* method to get Byte code class object
* @throws classnotfoundexception
/@Test public
void Demo1 () throws classnotfoundexception{
//Get class object three ways
//1. Class c1 = reflecttest.class;
2. Object
o = new Reflecttest () known;
Class C2 = O.getclass ();
3. Unknown class and object, know complete class name
String className = "Com.lc.reflect.ReflectTest";
Class C3 = Class.forName (className);
SYSTEM.OUT.PRINTLN (C1);
System.out.println (C2);
System.out.println (C3);
} </span></span>
Operation Construction Method
<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:14PX;" >/** * Gets the construction method exercise * @throws Exception/@SuppressWarnings ({"Unchecked", "Rawtypes"}) @Test public void Demo2 (
Throws exception{//Gets the person class byte code object String className = "Com.lc.reflect.Person";
Class C = class.forname (ClassName);
All construction methods are obtained by byte code object constructor[] Constructors = c.getconstructors ();
for (int i = 0; i < constructors.length i++) {System.out.println (constructors[i]);
}//Get the specified construction method constructor Constructordefault = C.getconstructor ();
System.out.println (Constructordefault); Sring.class is a String byte-code object Constructor constructor = C.getconstructor (String.class);
A construction method with a parameter type of string System.out.println (constructor);
To create the normal wording of an object instance: Person Person1 = new person ();
Person Person2 = new Person ("LC"); Use reflection to construct an instance of the person object reflectPerson1 = (person) constructordefault.newinstance (); Non-parametric construction method Person reflectperson1_1 = (person) c.newinstance (); Through CLass object directly newinstance, the target class parameterless constructor method Person ReflectPerson2 = (person) constructor.newinstance ("LC") will be called by default; parameter is a string-type construction method}</span></span>
Manipulating member variables
<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:14PX;" >/** * Practice of using reflection to manipulate class member variables/@SuppressWarnings ("Rawtypes") @Test public void Demo3 () throws exception{//object-oriented write
The method is the object invocation property, and reflection is just the opposite.
Person p = new person ("LC");
System.out.println ("The writing of the object invocation property =====>:" +p.getname ());
Use the Reflection Action class member variable--field class//1. The byte code object class C = Class.forName ("Com.lc.reflect.Person") of the target classes must be obtained; 2. Operation member instance variable name--get name to represent Field object field[] f1 = C.getfields ();
Gets all public member variables, including parent class inheritance for (int i = 0; i < f1.length i++) {System.out.println (f1[i)); } field[] F2 = C.getdeclaredfields ();
Gets all members of the current class definition, including private for (int i = 0; i < f2.length i++) {System.out.println (f2[i)); //Get Name member variable Field field = C.getdeclaredfield ("name");
The current field is private//SET private variable can access field.setaccessible (true); Gets the P object to specify the Name property value of Object value = Field.get (p);
Equivalent to P.getname ();
System.out.println ("The writing of reflection Operation member variable =====>" +value); /** * Use reflection to change the value of member variables (including private) * @throws Exception * * @Test public void Demo4 () throws exception{person P = new person ();
The value of SetName setting name in the P object is called//1. Gets the byte code object Class c = Class.forName ("Com.lc.reflect.Person"); 2. Operation SetName Gets the method object of the SetName object reflection object//string type parameter SetName methods Way SetName = C.getdeclaredmethod ("SetName",
String.class); Call the P object in SetName Setname.invoke (P, "sky");
Equivalent to P.setname ("Sky");
3. Read the value of name GetName method getName = C.getdeclaredmethod ("GetName"); Object name = Getname.invoke (p);
Equivalent to P.getname ();
System.out.println ("Reflection gets the value of the member variable ======>" +name); }</span></span>
General method of operation
<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:14PX;" >/**
* Operation Method Object
* @throws Exception * *
@Test public
void Demo5 () throws exception{
// Known string type full class name---Get Byte code object
String className = "Com.lc.reflect.Person";
Class C = class.forname (className);
Known class object, construct instance
Object obj = C.newinstance ();//Call parameterless Construct method
//Get specified property and method in bytecode object
//Get Name property
Field f = C.getdeclaredfield ("name");
Obtain SetName method
SetName = C.getdeclaredmethod ("SetName", string.class);
Modifies the value of the property and executes the corresponding method
f.setaccessible (true);
F.set (obj, "sky");
Setname.invoke (obj, "sky_lc");
The above code is equivalent to the following code person
p = new Person ();
P.name = "Sky";
P.setname ("SKY_LC");
} </span></span>
Java language Reflection provides a versatile way to dynamically link program components. It allows programs to create and control objects of any class without having to hard-code the target class in advance. These features make reflection particularly useful for creating libraries that collaborate with objects in a very common way. Java reflection is useful for enabling classes and data structures to dynamically retrieve relevant information by name and to allow manipulation of this information in running programs. This feature of Java is very powerful and is not available in other common languages, such as C, C + +, Fortran, or Pascal. Because reflection is much slower than direct code for field and method Access, reflection has a performance impact, but the extent of the performance problem depends on how reflection is used in the program. Slow performance will not be a problem if it acts as a relatively small part of the program's operation. Even the worst-case timings in the test show a reflection operation that only consumes a few microseconds. Performance issues become critical only when reflection is used in the core logic of performance-critical applications. Therefore, the rational use of reflection will greatly improve the versatility and reusability of our program.