reflection
- reflection
Java code and Java files
Class class name {member variable constructor member method Annotation Annotation} Java file requirements: 1. Normally one Java file corresponds to one Java class. 2. A Java file contains all the contents of the current Java code!!Copy the code
Java files and.class bytecode files
Java file firstjava.java through the compiler javac ==> javac firstjava.java ==> firstjava.class.class bytecode file?? Binary executable file. The.class bytecode file contains all the contents of the Java file. The.class bytecode file contains all the executable content of a Java program (annotations are not involved in compilation and execution).Copy the code
Class The memory location of the bytecode file
Class bytecode files and Java code relationships
Class Class related methods
Class Class.forName(String packageNameAndClassName) throws ClassNotFoundException; According to the full package name. ClassNotFoundException Not found Class object. Person p = new Person(); Person p = new Person(); P.gettclass () ==> Person Class object Class name. Class ==> The Person Class corresponds to the Class object.Copy the code
package com.qfedu.a_reflect; Ying @ ** / public Class GetClassObject {public static void main(String[] args) throws ClassNotFoundException { /* * Class Class.forName(String packageNameAndClassName) * throws ClassNotFoundException; */ Class cls1 = Class.forName("com.project.a_reflect.Person"); /* * Class object. GetClass (); */ Person person = new Person(); Class cls2 = person.getClass(); /* * Class Specifies the Class name. Class; */ Class cls3 = Person.class; /* * Whichever way the Class object of the specified Class is obtained, it is the same Class object * because the current Person Class has and only occupies code area space once in the current program. */ System.out.println("cls1 == cls2 : " + (cls1 == cls2)); System.out.println("cls2 == cls3 : " + (cls2 == cls3)); System.out.println("cls3 == cls1 : " + (cls3 == cls1)); }}Copy the code
The operator Constructor constructs the method class
Get the corresponding Class’s Constructor method Class object from the Class object
Constructor[] getConstructors(); Gets an array of all non-privatized constructor Class objects in the corresponding Class of the current Class object. Constructor[] getDeclaredConstructors(); Gets an array of all constructors in the corresponding Class of the current Class object, including privatized constructors. Constructor getConstructor(Class... parameterTypes); Gets the constructor of the specified parameter data type in the current Class object. The obtained constructor is the non-private constructor Class... ParameterTypes Class An indefinite parameter used to constrain the data type of the current constructor. For example: cls.getconstructor (); ==> Person(); Cls.getconstructor (int. Class, string.class) ==> Person(int, String) Constructor getDeclaredConstructor(Class... parameterTypes); Gets the constructor of the specified data type in the current Class object, including the private constructor. For example: For privatisation CLS type String constructor getDeclaredConstructor (String. Class) = = > private Person (String. The class)Copy the code
The Constructor class object creates the corresponding class object
Object newInstance(Object... parameters); Constructor class Object, execute the corresponding Constructor, create the corresponding class Object... It is an indefinite parameter. The data type must be Object. For example: the Person (s); Person p1 = (Person) constructor.newinstance (); Person(int, java.lang.String); Person p2 = (Person) constructor. NewInstance (10, "Java is really easy to learn ");Copy the code
package com.qfedu.a_reflect; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; Public class gettorObject {public static void getTorObject {public static void gettorObject {public static void gettorObject main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { /* * Class Class.forName(String packageNameAndClassName) * throws ClassNotFoundException; */ Class cls = Class.forName("com.project.a_reflect.Person"); Constructor[] constructors = cls.getconstructors (); /* * getConstructors(); for (Constructor constructor : constructors) { System.out.println(constructor); } System.out.println(); /* * get an array of all constructors in the corresponding Class of the current Class object, including private constructors. */ Constructor[] declaredConstructors = cls.getDeclaredConstructors(); for (Constructor constructor : declaredConstructors) { System.out.println(constructor); } System.out.println(); /* * 3. Get the constructor of the specified parameter data type in the current Class object. Constructor 1 = cls.getconstructor (); cls.getconstructor (); Constructor constructor2 = cls.getConstructor(int.class); Constructor constructor3 = cls.getConstructor(int.class, String.class); System.out.println(constructor1); System.out.println(constructor2); System.out.println(constructor3); /* * get the constructor of the specified data type in the current Class object. Including private Constructor * / Constructor constructor4 = CLS. GetDeclaredConstructor (String. Class); System.out.println(constructor4); System.out.println(); Person p1 = (Person) constructor1. NewInstance (); Person p2 = (Person) constructor2.newInstance(10); Person p3 = (Person) constructor3. NewInstance (20, "c "); System.out.println(p1); System.out.println(p2); System.out.println(p3); /* * Grant permission to violent reflection operation!! * setAccessible(boolean flag); */ constructor4.setAccessible(true); Person p4 = (Person) Constructor4. NewInstance ("Java is happy "); System.out.println(p4); }}Copy the code
Operate on the Method member Method class
Get the Method member of the corresponding Class from the Class object
Method[] getMethods(); Gets all non-privatized member methods of the current Class, including the non-privatized methods that can be used by subclasses that inherit from their parent Class, via a Class object call. Method[] getDeclaredMethods(); Call from a Class object to retrieve all member methods of the current Class, including privatized member methods, but excluding methods inherited from the parent Class. Method getMethod(String methodName, Class... parameterTypes); Call the Class object, according to the method name and the corresponding formal parameter list data type to get the corresponding member method, can get the parent Class inherited method, can not get the private member method for example: no parameter member method to get game(); cls.getMethod("game"); The parameterized member method gets game(String); cls.getMethod("game", String.class); Method getDeclaredMethod(String methodName, Class... parameterTypes); Private member methods can be obtained, but parent member methods cannot be obtained, using Class object calls based on method names and corresponding formal parameter list data types. For example: private member method testPrivate() without arguments; cls.getDeclaredMethod("testPrivate"); Private member method testPrivate(String) with arguments; cls.getDeclaredMethod("testPrivate", String.class);Copy the code
Operation Method class objects perform methods
Object invoke(Object obj, Object... parameters); Called through the Method class object to execute the corresponding Method. Object obj The class Object that executes the current method. Object... Parameters corresponds to the actual parameter list of the current methodCopy the code
package com.qfedu.a_reflect; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; Public class GetMethodObject {public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { /* * Class Class.forName(String packageNameAndClassName) * throws ClassNotFoundException; */ Class cls = Class.forName("com.project.a_reflect.Person"); /* * 1. Get all non-privatized member methods of the current Class, * including non-privatized methods that can be used by subclasses that inherit from their parent Class. */ Method[] methods = cls.getMethods(); for (Method method : methods) { System.out.println(method); } System.out.println(); [] declaredMethods = cls.getDeclaredMethods(); /* * declaredMethods = cls.getDeclaredMethods(); for (Method method : declaredMethods) { System.out.println(method); } System.out.println(); */ game1 = cls.getMethod("game"); Method game2 = cls.getMethod("game", String.class); System.out.println(game1); System.out.println(game2); System.out.println(); */ Method testPrivate1 = cls.getDeclaredMethod("testPrivate"); */ Method testPrivate1 = cls.getDeclaredMethod("testPrivate"); Method testPrivate2 = cls.getDeclaredMethod("testPrivate", String.class); System.out.println(testPrivate1); System.out.println(testPrivate2); System.out.println(); Cls.getconstructor ().newinstance (); cls.getconstructor ().newinstance (); game1.invoke(object); game2.invoke(object, "World Of Tank"); / * * give violence reflected operation permissions. * / testPrivate1 setAccessible (true); testPrivate2.setAccessible(true); testPrivate1.invoke(object); Testprivate2. invoke(object, "Tomato + cucumber + Egg + Shish Kebab "); }}Copy the code
Operates on the Field member variable class
Get the Field member variable object of the corresponding Class from the Class object
Field[] getFields(); Field[] getDeclaredFields(); GetField (String fieldName) getField(String fieldName); Obtain the corresponding member variable object based on the name of the member variable. The current member variable is not privatized. cls.getField("test"); Field getDeclaredField(String fieldName); [Violent reflection] Get a member variable object with the specified name, including private member variables. private int id; cls.getDeclaredField("name"); cls.getDeclaredField("id");Copy the code
Operation Field class object assignment value member variable
Field[] getFields(); Field[] getDeclaredFields(); GetField (String fieldName) getField(String fieldName); Obtain the corresponding member variable object based on the name of the member variable. The current member variable is not privatized. cls.getField("test"); Field getDeclaredField(String fieldName); [Violent reflection] Get a member variable object with the specified name, including private member variables. private int id; cls.getDeclaredField("name"); cls.getDeclaredField("id");Copy the code
package com.qfedu.a_reflect; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; Ying @ ** / public class GetFieldObject {public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { /* * Class Class.forName(String packageNameAndClassName) * throws ClassNotFoundException; */ Class cls = Class.forName("com.project.a_reflect.Person"); */ Field[] fields = cls.getFields(); for (Field field : fields) { System.out.println(field); } System.out.println(); DeclaredFields = cls.getDeclaredFields(); /* * declaredFields (); for (Field field : declaredFields) { System.out.println(field); } System.out.println(); */ Field test = cls.getField("test"); System.out.println(test); System.out.println(); Cls.getdeclaredfield ("id"); /* * cls.getDeclaredField("id"); Field name = cls.getDeclaredField("name"); System.out.println(id); System.out.println(name); System.out.println(); /* / obj = cls.getconstructor ().newinstance (); System.out.println(obj); test.set(obj, 100); System.out.println(obj); System.out.println(test.get(obj)); id.setAccessible(true); name.setAccessible(true); id.set(obj, 10); Name. Set (obj, "Big brother good power "); System.out.println(obj); System.out.println(id.get(obj)); System.out.println(name.get(obj)); System.out.println(); System.out.println(id.getType()); System.out.println(name.getType()); }}Copy the code
Violent reflex authorization
Class AccessibleObject public static void setAccessibleObject (AccessibleObject[] array, Boolean flag); A static utility called by class name that grants access to AccessibleObject or an array of subclasses of AccessibleObject. Field Method Constructor public void setAccessible(Boolean flag); Called from the AccessibleObject class object, single permission authorization, Field Method Constructor can be used.Copy the code
Case operation
String method is required. IO stream recommended character stream operation. 3. ==> String to other types of methods baidu Parse series methodsCopy the code
File name: studentinfo. TXT File content: ClassName =com.qfedu.a_reflect.Student name= li4 age=18 gender=false javaScore=59 webScore=59 dbScore=59Copy the code
package com.qfedu.a_reflect; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; @SuppressWarnings("all") public class ReflectDemo { public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, NoSuchFieldException { // 1. BufferedReader br = new BufferedReader(new FileReader("./data/ studentinfo.txt ")); String classInfo = br.readline (); String className = classInfo.substring(classInfo.indexOf("=") + 1); CLS = class.forname (className); Object obj = cls.getconstructor ().newinstance (); String info = null; Object value = null; While ((info = br.readline ())! Split = info.split("="); split = info.split("="); System.out.println(Arrays.toString(split)); Field Field = cls.getDeclaredField(split[0]); field.setAccessible(true); Class type = field.getType(); If (type.equals(string.class)) {value = split[1]; // field.set(obj, split[1]); Else if (type.equals(int.class)) {value = integer.parseint (split[1]);} else if (type.equals(int.class)) {value = integer.parseint (split[1]); Else if (type.equals(Boolean. Class)) {value = Boolean. ParseBoolean (split[1]); } field.set(obj, value); } System.out.println(obj); // Close the resource br.close(); }}Copy the code
The last
Welcome to pay attention to the public number: the future has light, receive a line of large factory Java interview questions summary + the knowledge points learning thinking guide + a 300 page PDF document Java core knowledge points summary! These are some of the things that the interviewer should ask during the interview. These include basics, Java collections, JVMS, multi-threaded concurrency, Spring principles, microservices, Netty and RPC, Kafka, diaries, design patterns, Java algorithms, databases, Zookeeper, distributed caching, data structures, and more.