Recent study hair is now very multifaceted. The basic knowledge is still very not strong, so for the structure, knowledge points, such as the kind of asking what to know, do what does not come out of that type. Some days ago. The teacher has been grasping the foundation, do everything from the simplest demo start, only understand the principle and then go with some advanced things such as the framework will understand more profound. The first thing that needs to be understood now is the reflection technology that basically every Java framework is using.
to understand reflection, you first need to understand the class loading process. See:
Our source code is compiled into bytecode and then executed in the JVM to generate class objects in memory by loading bytecode into the class loader. This class object includes the Field object (the generation of the member variable of the class), the constructor object (the constructor method generation of the Class), and the method object (methods generation of the Class).
When we get a class or an object, we can manipulate it through reflection, and then we'll look at the reflection:
- What is reflection
- Java Reflection refers to the ability of a program to access, detect, and alter its own state or behavior. is a key property of Java as a dynamic (or quasi-dynamic) language. This mechanism consents to the internal information of a class with a known name, regardless of the reflection APIs, in the execution of the procedure. Includes its modifiers (such as public, static, etc.), superclass (such as object), interfaces of implementation (such as cloneable), and all the information of fields and methods, You can change the contents of the fields or evoke methods at execution time. The Java reflection mechanism allows programs to load, detect, and use classes that are completely unknown during compilation. In other words, Java can load an execution to know the name of class. Get its full structure.
- Where is the reflection used?
- Used for frames and components, write out a common program with high reusability.
- If struts's form only needs to have the form object and the property name can use the reflection to the property to assign the value and the value to this kind of operation one method to be able to take care of. Suppose hibernate does not use a field for reflection mapping, then the compilation and result processing of each HQL will not be possible, and so on.
- How to use
- There are 3 ways to get a class bytecode object for each of the different situations we know about
- When the class name is known, it is obtained by the class name.
- When the object is known. Obtained by "object. GetClass"
- When the full class name (in string format) is known to contain the package name, it can be obtained by "class.forname (String)"
- The ability to construct object instances, get Property objects in objects, method objects, and constructor objects after getting a class bytecode object
- You will be able to manipulate the various objects required above. The operation of the increase and deletion check.
- What are the strengths and weaknesses?
Why use a reflection mechanism? Is it possible to create objects directly, which involves the concept of dynamic and static, Static compilation: Determines the type at compile time, binds the object, which is passed. Dynamic Compilation: Determines the type at execution time, binds the object. Dynamic compilation maximizes the flexibility of Java and embodies the application of polymorphism. To reduce the coupling between classes. in a word, the advantage of the reflection mechanism is the ability to dynamically create objects and compile, showing a great flexibility, especially in the development of Java EE , its flexibility is very obvious. For example, a large-scale software, it is impossible to design the perfect one at a time, when the program has been translated, published, when the discovery needs to update some features, we can not want users to uninstall, and then install a new version number, if such words. This software is definitely not used by many people. Using static words, the whole program needs to be compiled once again talent enough to achieve the function of the update, and the use of reflection mechanism, it can not unload, only need to be executed dynamically in the creation and compilation, you can achieve the power .
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. This type of operation is always slower than just running the same operation directly.
- Sample Example
- How to get a class bytecode object
<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:14PX;" >/** * method to get the byte code class object * @throws classnotfoundexception */@Testpublic void Demo1 () throws classnotfoundexception{// Get the class object three ways//1. Known classes class C1 = REFLECTTEST.CLASS;//2. Known objects object o = new Reflecttest (); Class C2 = O.getclass ();//3. Unknown class and object, knowing the full 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;" >/** * Get Construction method Exercise * @throws Exception */@SuppressWarnings ({"Unchecked", "Rawtypes"}) @Testpublic void Demo2 () throws Exc eption{//Gets the person class byte-code object String className = "Com.lc.reflect.Person"; Class C = class.forname (className);//The entire construction method is obtained through the bytecode object constructor[] constructors = c.getconstructors (); for (int i = 0; I &l T Constructors.length; i++) {System.out.println (constructors[i]);} Gets the specified constructor method constructor Constructordefault = C.getconstructor (); System.out.println (Constructordefault);//sring.class is a byte-code object of string Constructor constructor = C.getconstructor ( String.class); Construction method with parameter type string System.out.println (constructor);//Create object instance in normal notation: person person1 = new person (); Person Person2 = new Person ("LC");//Use reflection to construct an instance of the person object reflectPerson1 = (person) constructordefault.newinstance () ; Non-participatory construction method Person reflectperson1_1 = (person) c.newinstance (); Directly newinstance through the class object. The target class will be called by default no-participant method person ReflectPerson2 = (person) Constructor.newinstanCE ("LC");//The construction method of the string type}</span></span>
<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:14PX;" >/** * Practice of using reflection to manipulate class member variables */@SuppressWarnings ("Rawtypes") @Testpublic void Demo3 () throws exception{//object-oriented notation is an object invocation property. And the reflection is just the opposite. Person p = new person ("LC"); System.out.println ("Object Invocation property =====>:" +p.getname ());//Use the Reflection Operation class member Variable--field class//1. The byte-code object of the target class must be obtained class C = Class.forName ("Com.lc.reflect.Person");//2. Action member instance variable name--get name represents Field object Field[] f1 = C.getfields (); Gets the full public member variable. Contains parent class inheritance for (int i = 0; i < f1.length; i++) {System.out.println (f1[i]);} field[] F2 = C.getdeclaredfields (); Gets all the members of the current class definition. Contains privatefor (int i = 0; i < f2.length; i++) {System.out.println (f2[i]);} Get the Name member variable Field field = C.getdeclaredfield ("name"); The current field is private//setting the private variable to be able to access field.setaccessible (TRUE);//Gets the P object to specify the value of the Name property of the Object value = Field.get (p); Equivalent to P.getname (); System.out.println ("=====>" of the reflection Operation member variable +value); /** * Use reflection to change the value of a member variable (including private) * @throws Exception */@Testpublic void Demo4 () throws Exception{person p = new person ();//Invoke P object in s Etname setting NAThe value of me is//1. Gets the Bytecode object Class c = Class.forName ("Com.lc.reflect.Person"),//2. Operation SetName Get SetName Object Reflection object's method object// The String type parameter SetName method setName = C.getdeclaredmethod ("SetName", string.class);//calls the P object Setnamesetname.invoke (P, " Sky "); Equivalent to P.setname ("Sky");//3. Reads 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;" >/** * Action Method Object * @throws Exception */@Testpublic void Demo5 () throws exception{//known string type full class name---Get Bytecode object string Classna me = "Com.lc.reflect.Person"; Class C = Class.forName (className);//Known class object. Constructs an instance of object obj = C.newinstance (); Call the non-participating constructor//Get the specified property and method in the Bytecode object//Get the name attribute field F = C.getdeclaredfield ("name");//Get SetName method SetName = C.getdeclaredmethod ("SetName", string.class);//Change the value of the property, run the corresponding method f.setaccessible (true); F.set (obj, "sky"); Setname.invoke (obj, "SKY_LC");//The code above 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 agrees that the program creates and controls objects of whatever class, without having to hardcode the target class in advance. These features make reflection especially useful for creating libraries that work in a very common way with objects. Java reflection is useful in that it enables classes and data structures to dynamically retrieve relevant information by name and agrees to manipulate the information in executing programs. This is a powerful feature of Java, and it is not available in other 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 degree of performance issues depends on how the reflection is used in the program. Assume that it is a relatively small part of program execution. Slow performance will not be a problem. Even if the worst-case timing chart in the test is displayed, the reflection operation only consumes a few microseconds.
Performance issues become critical only when reflection is used in the core logic of performance-critical applications.
So. Reasonable use of reflection will greatly improve the universality and reusability of our program.
Java Reflection-Recognize again