Author: Mars shichiro
https://www.cnblogs.com/hxsyl
I concept
Reflection is to map various components of Java into corresponding Java classes.
Class Class is constructed by private JVM Create.
Reflection is a feature of the Java language, which allows programs to check themselves and operate on internal members at run time (not at compile time). For example, it allows a Java class to get all its member variables and methods and display them. This capability of Java may not be widely used in practical applications, but it does not exist in other programming languages. For example, in Pascal, C, or c++, there is no way to obtain information about function definitions in a program. (from Sun)
JavaBean is one of the practical applications of reflection. It allows some tools to visualize the operation of software components. These tools dynamically load and obtain the properties of Java components (classes) through reflection.
Reflection has existed since 1.2. The following three frameworks will use the reflection mechanism, involving the Class "Class". It is impossible to directly new CLass(), whose object is a bytecode in memory The
Instances of the Class represent classes and interfaces in a running Java application. Enumeration is a kind and annotation is an interface. Each array belongs to a Class mapped as a Class object, which is shared by all arrays with the same element type and dimension.
The basic Java types (boolean, byte, char, short, int, long, float, and double) and the keyword void are also represented as class objects. Class has no public constructor.
The Class object is automatically constructed by the Java virtual machine and by calling the defineClass method in the Class loader when the Class is loaded.
Person p1 = new Person(); //Bytecode can be obtained by the following three methods CLass c1 = Date.class(); p1.getClass(); //If it exists, load it. Otherwise, create a new one. The third one is often used. The name of the class does not need to be known when writing the source program, and it will be passed back at run time Class.forName("java.lang.String");
Class.forName() Bytecode has been loaded into java virtual machine to get bytecode; The bytecode has not been generated in the java virtual machine and loaded by the class loader. The loaded bytecode is buffered into the virtual machine. The
In addition, you can pay attention to the wechat official account Java technology stack reply: JVM, get the series of JVM tutorials I sorted out. They are all dry goods.
Consider the following simple example to see how reflection works.
import java.lang.reflect.*; public class DumpMethods { public static void main(String args[]) { try { Class c = Class.forName("java.util.Stack"); Method m[] = c.getDeclaredMethods(); for (int i = 0; i < m.length; i++) System.out.println(m[i].toString()); } catch (Throwable e){ System.err.println(e); } } } public synchronized java.lang.Object java.util.Stack.pop() public java.lang.Object java.util.Stack.push(java.lang.Object) public boolean java.util.Stack.empty() public synchronized java.lang.Object java.util.Stack.peek() public synchronized int java.util.Stack.search(java.lang.Object)
This lists java Util The names of the methods of the stack class and their qualifiers and return types. This program uses Class.forName Load the specified class, and then call getdeclaraedmethods to get the list of methods defined in this class. Java Lang.reflect Methods is a class used to describe a single method in a class.
The following example uses a Class object to display the Class name of an object:
void printClassName(Object obj) { System.out.println("The class of " + obj + " is " + obj.getClass().getName()); }
You can also use a Class literal (JLS Section 15.8.2) to obtain a Class object of a specified type (or void). For example:
System.out.println("The name of class Foo is: "+Foo.class.getName());
When there are no object instances, there are two main methods.
//Two ways to get class types Class cls1 = Role.class; Class cls2 = Class.forName("yui.Role");
Note that in the second method, the parameter in forName must be the complete Class name (package name + Class name), and this method needs to catch exceptions. Now that you have cls1, you can create an instance of the Role Class. Using the newInstance method of the Class is equivalent to calling the default constructor of the Class.
Object o = cls1.newInstance(); //Create an instance //Object o1 = new Role()// Equivalent to the above method
II common method
1.isprimitive (judge whether it is a basic type of bytecode)
public class TestReflect { public static void main(String[] args) { // TODO Auto-generated method stub String str = "abc"; Class cls1 = str.getClass(); Class cls2 = String.class; Class cls3 = null;//Must add null try { cls3 = Class.forName("java.lang.String"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(cls1==cls2); System.out.println(cls1==cls3); System.out.println(cls1.isPrimitive()); System.out.println(int.class.isPrimitive());//Determines whether the specified Class object represents a basic type. System.out.println(int.class == Integer.class); System.out.println(int.class == Integer.TYPE); System.out.println(int[].class.isPrimitive()); System.out.println(int[].class.isArray()); } }
Results:
true true false true false true false true
2.getConstructor and getConstructors()
There is no sequence for constructing methods in java, which is distinguished by types and the number of parameters. The
public class TestReflect { public static void main(String[] args) throws SecurityException, NoSuchMethodException { // TODO Auto-generated method stub String str = "abc"; System.out.println(String.class.getConstructor(StringBuffer.class)); } }
3. The file class represents a member variable in a class.
import java.lang.reflect.Field; public class TestReflect { public static void main(String[] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, Exception { ReflectPointer rp1 = new ReflectPointer(3,4); Field fieldx = rp1.getClass().getField("x");//Must be x or y System.out.println(fieldx.get(rp1)); /* * private The member variable of must use getDeclaredField and setAccessible(true), otherwise it can't be seen */ Field fieldy = rp1.getClass().getDeclaredField("y"); fieldy.setAccessible(true);//Violent reflex System.out.println(fieldy.get(rp1)); } } class ReflectPointer { public int x = 0; private int y = 0; public ReflectPointer(int x,int y) {//alt + shift +s is equivalent to right clicking source super(); // TODO Auto-generated constructor stub this.x = x; this.y = y; } }
III Typical examples
1. change b in all String type member variables to a.
import java.lang.reflect.Field; public class TestReflect { public static void main(String[] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, Exception { ReflectPointer rp1 = new ReflectPointer(3,4); changeBtoA(rp1); System.out.println(rp1); } private static void changeBtoA(Object obj) throws RuntimeException, Exception { Field[] fields = obj.getClass().getFields(); for(Field field : fields) { //if(field.getType().equals(String.class)) //Since there is only one copy of bytecode, it is not accurate to use equals semantics if(field.getType()==String.class) { String oldValue = (String)field.get(obj); String newValue = oldValue.replace('b', 'a'); field.set(obj,newValue); } } } } class ReflectPointer { private int x = 0; public int y = 0; public String str1 = "ball"; public String str2 = "basketball"; public String str3 = "itcat"; public ReflectPointer(int x,int y) {//alt + shift +s is equivalent to right clicking source super(); // TODO Auto-generated constructor stub this.x = x; this.y = y; } @Override public String toString() { return "ReflectPointer [str1=" + str1 + ", str2=" + str2 + ", str3=" + str3 + "]"; } }
2. write a program to call the main method in the class according to the class name provided by the user.
Why use reflection?
import java.lang.reflect.Field; import java.lang.reflect.Method; public class TestReflect { public static void main(String[] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, Exception { String str = args[0]; /* * This will cause the array subscript to be out of range, because there is no such character array at all * Right click to enter b.Inter (full class name) in run as configurations arguments * */ Method m = Class.forName(str).getMethod("main",String[].class); //Both of the following methods can be used. The main method requires a parameter m.invoke(null, new Object[]{new String[]{"111","222","333"}}); m.invoke(null, (Object)new String[]{"111","222","333"});//This shows that the array is also an Object /* * m.invoke(null, new String[]{"111","222","333"}) * The above cannot be used, because java will automatically unpack */ } } class Inter { public static void main(String[] args) { for(Object obj : args) { System.out.println(obj); } } }
**3 Simulation** instanceof Operator
class S { } public class IsInstance { public static void main(String args[]) { try { Class cls = Class.forName("S"); boolean b1 = cls.isInstance(new Integer(37)); System.out.println(b1); boolean b2 = cls.isInstance(new S()); System.out.println(b2); } catch (Throwable e) { System.err.println(e); } } }
In this example, you create a Class object of Class S, and then check whether some objects are instances of Class S. Integer(37) is not, but new S() is.
Recommended reading: instanceof,isInstance,isAssignableFrom
IV Method class
Represents a method in a class (not an object).
import java.lang.reflect.Field; import java.lang.reflect.Method; /* * Drawing a circle on the blackboard involves three objects. Drawing a circle requires the center and radius of the circle, but it is private. The method of drawing a circle * It is not appropriate to assign to others. * * When the driver steps on the brake, the driver only gives instructions to the train, and the brake action still needs to be completed by the train. * * Interviews often test object-oriented design, such as when people close the door, people just push the door. * * This is the expert mode: whoever owns the data is an expert, and the method is assigned to whom */ public class TestReflect { public static void main(String[] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, Exception { String str = "shfsfs"; //com at the beginning of the package indicates that it is used internally by sun, and java is the user's Method mtCharAt = String.class.getMethod("charAt", int.class); Object ch = mtCharAt.invoke(str,1);//If the first parameter is null, it must be a static method System.out.println(ch); System.out.println(mtCharAt.invoke(str, new Object[]{2}));//1.4 grammar } }
V Reflection of array
The Array utility class is used to complete the reflection operation of an Array.
The same type and latitude have the same bytecode.
Int.class and integer Class is not the same bytecode, integer TYPE, TYPE represents the bytecode int.class==integer TYPE.
import java.util.Arrays; /* * From this example, we can see that even if the bytecode is the same, the objects are not necessarily the same. It is not the same thing at all * */ public class TestReflect { public static void main(String[] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, Exception { int[] a = new int[3]; int[] b = new int[]{4,5,5};//Length cannot be specified after direct assignment, otherwise CE int[][] c = new int[3][2]; String[] d = new String[]{"jjj","kkkk"}; System.out.println(a==b);//false System.out.println(a.getClass()==b.getClass());//true //System Out Println (a.getclass() ==d.getclass())// There is no way to compare bytecode a with cd System.out.println(a.getClass());//Output class [I System.out.println(a.getClass().getName());//Output [i, brackets for array, I for integer System.out.println(a.getClass().getSuperclass());//Output class java Lang.Object System.out.println(d.getClass().getSuperclass());//Output class java Lang.Object //Since the parent classes are all objects, the following are all possible Object obj1 = a;//No, it's Object[] Object obj2 = b; Object[] obj3 = c;//A one bit array of a basic type can only be regarded as an Object, but it can also be regarded as an Object[] Object obj4 = d; //Note the difference between asList handling int[] and String[] System.out.println(Arrays.asList(b));//1.4 there are no variable parameters, but arrays are used[[ I@1bc4459 ]The System.out.println(Arrays.asList(d));//[jjj, kkkk] } }
Vi Concluding remarks
The above is the simple use of the reflection mechanism. Obviously, those who have studied spring must understand why we can get the specified methods and variables through the configuration file. When we create objects, we pass in string s. It seems that we produce for you what you need. We also use objects all the time. This shows that the dynamic characteristics of the java language and the dependency are greatly reduced.
The copyright of this article belongs to the author Mars shijilang. Reprint and commercial use are welcome. However, this statement must be retained without the consent of the author, and a link to the original text must be given in an obvious position on the page of the article. Otherwise, the right to investigate legal liabilities is reserved
Follow the official account Java technology stack and reply to the "interview" to get the most comprehensive 2020 test questions and answers I sorted out.
It is recommended to go to my blog to read more:
1.Java JVM, collections, multithreading, new features series tutorials
2.Spring MVC, Spring Boot, Spring Cloud series tutorials
3.Maven, Git, Eclipse, Intellij IDEA series tool tutorial
4.The latest interview questions from Java, backend, architecture, Alibaba and other big companies
Feel good, don't forget to like + forward!