Basic concepts of Reflection
If you are working with a class, if it is normal, you must follow these steps:
-
- Importing the package containing the class using Import; (class: Java.lang.Class)
- Define the object explicitly using the class name or the pretext name;
- Class object instantiation through the keyword new; (Construction method: Java.lang.reflect.Constructor);
- The resulting object can use the object. property to make a call to a property in the class (attribute: Java.lang.reflect.Field);
- Calling the class by "object. Method ()" Method: Java.lang.reflect.Method;
The reflection process does not require an object of a definite type, and all objects use object to represent
1. The method in the class can be called directly using the mixture of object and reflection mechanism.
All methods in the Object class and considerations for each method use:
- object Cloning : Protected object clone? () throws clonenotsupportedexception creates and returns a copy of this object. The exact meaning of "copy" may depend on the class of the object.
- Why is the Clone method returning an object? A: Because the cloning method may be used for all class objects, in order to unify the parameters with object
- The class of the cloned object must implement the Java.lang.Cloneable interface and the subclass only needs to continue to invoke the Clone method of object to successfully implement the cloning operation;
- Object Output : Public String toString? () returns the string representation of the object.
- The ToString () method is called by default when the object is output directly
- Cause: Since we usually directly System.out.println (); To directly output the object, we open the source code to see why the default call to the ToString () method
Find the print output method in the PrintStream class as follows
public void print (Object obj) {
Write (string.valueof (obj));
}
Can see him in the output of the time called the string valueOf method, the following open the valueOf method source code
public static String valueOf (Object obj) {
return (obj = = null)? "Null": obj.tostring ();
From which we can see that if the incoming object is not NULL, the ToString () method is called automatically and then returns
- Object Comparison : public boolean equals? (Object obj) indicates whether some other object is equal to this.
- When is this method implicitly called??
- When we save the set set, we rely on hashcode () and Equals () to determine whether the object is duplicated;
- get the object's hash code : public boolean equals? (Object obj) indicates whether some other object is equal to this.
- Can be understood as a unique encoding for each object, the comparison will first determine whether the encoding is the same, and then call the Equals method to determine whether the same
- Get Class object : Public final class<?> GetClass? () returns the
Object run-time class for this.
- The object's reflection operation is performed by an already instantiated object;
- thread wait : Public final void wait? () throws interruptedexception causes the current thread to wait until another thread invokes the object's
notify() method or notifyAll() method. In other words, the behavior of this method is like simply executing a call wait(0) .
- When executed to this code, the thread waits for execution until it executes
notify() ornotifyAll()方法来唤醒线程;
- one thread wakes up : public final void notify? () wakes a single thread that is waiting for the object monitor.
- All threads Wake up : public final void Notifyall? () wakes all threads that are waiting for the object monitor.
- release before garbage collection : protected void Finalize? () throws Throwable is obsolete . the finalization mechanism is inherently problematic. finalization may cause performance issues, deadlocks, and hangs.
- Called by default when using GC to reclaim useless garbage space;
Class
The class class is the source of the operation of the entire reflection, and the classes are defined as follows:
Public Final class class<t> //reflected generics are almost useless, use "? "extends Objectimplements Serializable, genericdeclaration, Type, Annotatedelement
If you want to work with class classes, you must first produce instantiated objects for class classes, and there are three ways to instantiate objects of the Claas class.
-
- The object class provides a way to return the class object: Public final class<?> GetClass? ();
- With "class. Class" obtained, the most in the future is on hibernate;
- Using the static method of class, public static class<?> forname? (String className) throws ClassNotFoundException returns the object associated with the class or interface given the string name
Class .
In the case of programmers, the most used method must be the forname () method, but if the user uses class. The factory design pattern is best used to solve the coupling problem using the reflection mechanism.
Instantiating an object with reflection
Class classes If you use the forname () method, you can use the Newinstance () method defined by class classes to invoke the parameterless constructor in the class by default
Public T newinstance? () throws Instantiationexception, illegalaccessexception, this generic type is not used
Code Demo: Here is unacceptable to this return value,
Here is the code implementation that solves the above error: from there we can see that we don't have to instantiate the object with new, as long as we have the full name of a class and we can instantiate the object
Public classR { Public Static voidMain (string[] args) throws Exception {Class<?> CLS = Class.forName ("test. Student"); //The newinstance () method started directly with JDK 1.9 is obsolete and can be used to call the Newinstance () method in the following way//The equivalent of the keyword new instantiation object. Equivalent to Object newinstance = new Student ();Object newinstance =Cls.getdeclaredconstructor (). newinstance (); }}classstudent{ PublicStudent () {System. out. println ("Construction Method Student"); } }
Execution Result: Construction method Student
However, if you instantiate an object using reflection, you must require that there is no parameter construction method in the class, because the newinstance() method can only find no parameters. If there is no parameterless constructor as follows:
Exception in thread "main" Java.lang. nosuchmethodexception:
What if you want to find a non-parametric construct? Operation Construction Method
How to construct the operation:
In order to solve the nosuchmethodexception error, this time this can be obtained in the class of the construction method, passing the required parameters before it can be used.
The class class defines an operation that can obtain a constructor method in a class:
-
- public constructor<t > getconstructor? ( class<?>... parametertypes ) (focus on use)
throws Nosuchmethodexception, Secu Rityexception
Returns a Constructor object, in time gets the construct of the parameter in the class , which reflects the specified public constructor of the class represented by this class object.
-
Public class<? >[] getdeclaredclasses? () throws SecurityException
Returns an Class array of objects, which are all constructs , reflecting all Class classes and interfaces declared as members of the class represented by this object.
Code Demo: Get all the construction methods in the string.
import Java.lang.reflect.Constructor; Public classGetstringconstructor { Public Static voidMain (string[] args) throws Exception {Class<?> forname = Class.forName ("java.lang.String"); Constructor<?>[] Constructors = forname.getconstructors ();//Get all constructs for(inti =0; i < constructors.length; i++) {System. out. println (Constructors[i]); } }}
Execution Result:
Public java.lang.String (byte[])
Public java.lang.String (Byte[],int,int)
Public java.lang.String (Byte[],java.nio.charset.charset)
Public java.lang.String (byte[],java.lang.string) throws Java.io.UnsupportedEncodingException
Public java.lang.String (Byte[],int,int,java.nio.charset.charset)
Public java.lang.String (Java.lang.StringBuilder)
Public java.lang.String (Java.lang.StringBuffer)
Public java.lang.String (Char[],int,int)
Public java.lang.String (char[])
Public java.lang.String (java.lang.String)
Public java.lang.String ()
Public java.lang.String (byte[],int,int,java.lang.string) throws Java.io.UnsupportedEncodingException
Public java.lang.String (Byte[],int)
Public java.lang.String (Byte[],int,int,int)
Public java.lang.String (Int[],int,int
so if you want to make a call to construct a method now, you have to put the focus in the Contructor class.
Public T newinstance? (Object ... initargs) Throws Instantiationexception, illegalaccessexception, illegalargumentexception, using this Constructor The object represents the constructor that creates and initializes a new instance of the constructor's declaration class, using the specified initialization parameters.
Code implementation: Instantiating the student object just now
import Java.lang.reflect.Constructor;
Class student{
Public Student (String str) {
System.out.println ("Construction method Student:" +STR);
}
} Public classGetstringconstructor { Public Static voidMain (string[] args) throws Exception {Class<?> forname = Class.forName ("test. Student"); Constructor<?> constructors = Forname.getconstructor (String.class);//From this you can see that the parameter type of the constructor method you want to call is always available constructors.newinstance ("Pure rookie-java-reflex"); }}
Execution Result: Construction method Student: Pure rookie-java-reflex time:40.00
Analyzing the connection between simple Java classes and reflection
Solving the problem of too much servlet code with reflection
Use reflection to solve Factory mode, agent design mode operation
Dynamic proxy design mode, dynamic proxy design mode implemented by Cglib
Writing annotation operations using annotion
java--Reflex