This is the 11th day of my participation in Gwen Challenge

preface

This is an introduction to Reflection technology in Java. Learn about the basic concepts of reflection. Reflection will be covered in more detail later

Overview of reflection

Java is not a dynamic language, but Java can be called a quasi-dynamic language because of its reflection mechanism. And this reflection mechanism is key to Java being seen as a dynamic language. The Reflection mechanism allows programs to retrieve the internal messages of any class through the Reflection API during execution and to directly manipulate the internal properties and methods of any object. After the Class is loaded, an object of type Class (one Class object per Class) is generated in the method area of heap memory, which contains the complete structure information of the Class. We can see the structure of the class through this object. This object is like a mirror through which you can see the structure of the class, hence our figurative name: reflection.

Advantages: Can achieve dynamic object creation and compilation, reflecting a great deal of flexibility.

Disadvantages: Performance impact, using reflection is basically a parsing operation, we can tell the JVM what we want to do and it meets our requirements. This type of operation is always slower than performing the same operation directly.

Get class objects

2.1 Java code analysis

Java code goes through three stages in a computer.

Stage 1: source code stage. A POJO class written by A programmer, let’s say A, can contain member variables, constructors, and member methods. The class is then compiled by Javac to produce an A.class bytecode file.

The second stage: class object stage. This stage is loaded by the ClassLoader to get an object of class class. This object contains member variables, constructors, and member methods. A class produces only one class object.

Phase 3: runtime phase. Objects are created through these methods of the class class. The essence of reflection is to get the class object and then get the student object in reverse.

2.2 How do I get class objects

Method 1: getClass () method of the Object class

 Person p = new Person();
 Class c = p.getClass();
Copy the code

Method 2: Any data type has a “static” class attribute.

Class objects of all types:

public class Test03 { public static void main(String[] args) { Class c1 = Object.class; Class c2= Comparable. Class; Class c3=String[]. Class; // array c4=int[][].class; Class c5=Override. Class; Class c6= integer.class; Class c7= ElementType. Class; // Enumeration Class c8=void. Class; / / short Class c9 = Class. The Class; //class System.out.println(c1); System.out.println(c2); System.out.println(c3); System.out.println(c4); System.out.println(c5); System.out.println(c6); System.out.println(c7); System.out.println(c8); System.out.println(c9); }}Copy the code

Output result:

class java.lang.Object
interface java.lang.Comparable
class [Ljava.lang.String;
class [[I
interface java.lang.Override
class java.lang.Integer
class java.lang.annotation.ElementType
void
class java.lang.Class
Copy the code

Method 3 (common) : Static method of Class: forName (String className)

Class c4 = Class.forName("com.xiaolei.Person");
Copy the code

Get the constructor by reflection and use it

Create a person class:

Public class Person {// Define three member variables private String name; int age; public String address; public Person() { } private Person(String name){ this.name=name; } Person(String name, int age) { this.name = name; this.age = age; } public Person(String name, int age, String address) { this.name = name; this.age = age; this.address = address; } public void show() {system.out.println ("show!") ); Public void method(String s) {system.out.println ("method:" + s); } public String getString(String s,int I){return s+"-- "+ I; } private void function(){system.out.println ("function!"); ); } @override public String toString() {return "Person[name="+name+",age="+age+",address="+address+"]"; }}Copy the code

The test class:

package fqy1; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; Public Constructor[] getConstructors() : public Constructor[] getConstructors() : public Constructor[] getDeclaredConstructors() : Get all constructors (private, protected, default, public) 2). Get a single method and call: public Constructor getConstructor(Class... ParameterTypes: gets a single "public" Constructor specified: public Constructor getDeclaredConstructor(Class... ParameterTypes: gets "a constructor" that can be private, protected, default, or public. Call Constructor: Constructor-->newInstance(Object... Initargs) newInstance() con.newInstance(" zhangsan", 20); */ public class ReflectDemo2 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {// Get bytecode file object Class c1= class.forname (" fqy1.person "); Public Constructor[] getConstructors(); public Constructor[] getConstructors(); public Constructor[] getConstructors(); Constructor[] cons = c1.getConstructors(); for(Constructor con:cons){ System.out.println(con); } public Constructor[] constructors () : // getConstructors (); Constructor[] cons2 =c1.getDeclaredConstructors(); for(Constructor con:cons2){ System.out.println(con); } // public Constructor getConstructor(Class... parameterTypes): // A: create A bytecode file object first // B: create A constructor object from the bytecode file object // C: create an instance object from the constructor object. Gets the specified single "common" constructor :"); Constructor con3= c1.getConstructor(null); Object obj= con3.newinstance (); System.out.println(obj); /* Fourth: requirements: Public person (String name,int age,String address) */ system.out.println (" "); Constructor con4=c1.getConstructor(String.class,int.class,String.class); Object obj2=con4.newInstance(" Xu Lei ",18," Wuhan "); System.out.println(obj2); / / system.out.println (); / / system.out.println (); Constructor con5=c1.getDeclaredConstructor(String.class); // Violence access con5.setAccessible(true); Obj2 = con5. NewInstance (" cat "); //IllegalArgumentException: System.out.println(obj2); }}Copy the code

Background output:

A, access to all public constructor: public fqy1. Person (Java. Lang. String, int, Java. Lang. String) public fqy1. Person () 2, for all the constructor: public fqy1.Person(java.lang.String,int,java.lang.String) fqy1.Person(java.lang.String,int) private Fqy1.person (java.lang.string) public fqy1.person () Person[name=null,age=0,address=null] Person[name= xu Lei,age=18,address= wuhan] Person [name = cat cat, age = 0, address = null]Copy the code

4. Get member variables by reflection and use them

1).field [] getFields(): obtain all public fields. 2).field [] getDeclaredFields(): obtain all public fields.

Public Field getField(String fieldName): getField(String fieldName): getField(String fieldName); Public Field getDeclaredField(String fieldName)

Field –> public void set(Object obj,Object value):

Parameter description: 1. Obj: indicates the object of the field to be set. Value: the value to be set for the field;

The test class:

public class ReflectDemo3 { public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {// Create class object class c2= class.forname (" fqy1.person "); //Field[] getFields(): get all public fields system.out.println (" first: get all public member variables: "); Field[] field=c2.getFields(); for(Field f:field){ System.out.println(f); } //Field[] getDeclaredFields(): getsystem.out.println (): getDeclaredFields(); Field [] field2=c2.getDeclaredFields(); for(Field f:field2){ System.out.println(f); } //public Field getField(String fieldName): get a "public" Field; //Field --> public void set(Object obj,Object value): system.out.println (" 一 : obtain a public Field and assign a value: "); Constructor con = c2.getconstructor (); Object obj =con.newInstance(); Field field3=c2.getField("address"); Field3. Set (obj, "wuhan"); // Set the f field of the object to "wuhan" system.out.println (obj); // Get name and assign system.out.println (" fourth: Get private variable and assign "); Field field4=c2.getDeclaredField("name"); field4.setAccessible(true); Field4. Set (obj, "frank xu lei"); System.out.println(obj); }}Copy the code

Background output:

Public java.lang.String fqy1.person.address public java.lang.String fqy1.person.address Private java.lang.String fqy1.person. name int fqy1.person. age public java.lang.String fqy1.person. address 第 3: Person[name=null,age=0,address= wuhan] Person[name= xu Lei,age=0,address= Wuhan]Copy the code

5. Get member methods by reflection and use them

5.1 Batch:

Public Method[] getMethods(): getMethods(); Public Method[] getDeclaredMethods(): getDeclaredMethods(): getDeclaredMethods(): getDeclaredMethods(): getDeclaredMethods(): getDeclaredMethods(): getDeclaredMethods()Copy the code

5.2 Obtaining a Single:

public Method getMethod(String name,Class<? >... ParameterTypes: parameter name: method name; Class ... Public Method getDeclaredMethod(String name,Class<? >... parameterTypes)Copy the code

[Note] : The first parameter represents the method name, the second parameter represents the class type of the method parameter, the return value of this method is Object, the first parameter represents the Object, the second parameter represents the actual parameter of the call method.

5.3 Calling methods:

Method --> public Object invoke(Object obj,Object... Args): parameter description: obj: object to call the method; Args: arguments passed when the method is called;Copy the code

Test member method:

/* Test member method:  */ public class ReflectDemo4 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {// Create class object class C = class.forname (" fqy1.person "); //public Method[] getMethods(): getMethods(); System.out.println("------ first: get all public methods -------"); Method []m=c.getMethods(); for(Method method:m){ System.out.println(method); } / / public Method [] getDeclaredMethods () : System. Out. The println (" -- -- -- -- -- -- -- -- -- the second: get all the way -- -- -- -- -- -- -- -- "); Method[] m2=c.getDeclaredMethods(); for(Method method:m2){ System.out.println(method); } Constructor con=c.getConstructor(); Object obj=con.newInstance(); System. Out. Println (" -- -- -- -- -- -- -- -- the third for a single a no-parameter methods and use -- -- -- -- -- -- -- -- -- -- "); // call show Method m1= c.goetMethod ("show"); //obj.m1(); Error / / m1. Invoke (obj); / / call the method of object obj m1 System. Out. The println (" -- -- -- -- -- the fourth, there are arguments to get a single parameter and use -- -- -- -- -- -- -- -- -- -- - "); Method m3=c.getMethod("method", String.class); m3.invoke(obj,"hello"); System. The out. Println (" -- -- -- -- -- 5, access method with multiple parameters and the use of -- -- -- -- -- "); Method m4=c.getMethod("getString", String.class, int.class); Object objectString=m4. Invoke (obj," Xu Lei ",18); // Return type object, remember! System.out.println(objectString); System. Out.println (" -- -- -- -- -- the sixth. Get the private method and use ----"); Method m5=c.getDeclaredMethod("function"); m5.setAccessible(true); m5.invoke(obj); }}Copy the code
The first: -- -- -- -- -- - ------- public java.lang.string fqy1.person.toString () public void fqy1.person.method (java.lang.string) public java.lang.String fqy1.Person.getString(java.lang.String,int) public void fqy1.Person.show() public final void java.lang.Object.wait() throws java.lang.InterruptedException public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException public boolean java.lang.Object.equals(java.lang.Object) public native int java.lang.Object.hashCode() public final native java.lang.Class java.lang.Object.getClass() public final native void Java.lang.object. Notify () public final native void Java lang. Object. The notifyAll () -- -- -- -- -- -- -- -- -- the second: -------- public java.lang.string fqy1.person.toString () private void fqy1.person.function () public void fqy1.person.function () public void fqy1.person.function ( fqy1.Person.method(java.lang.String) public java.lang.String fqy1.Person.getString(java.lang.String,int) public void Fqy1. Person. The show () -- -- -- -- -- -- -- -- the third for a single a no-parameter methods and use -- -- -- -- -- -- -- -- -- -- show! -- -- -- -- -- the fourth, there are arguments to get a single parameter and use -- -- -- -- -- -- -- -- -- -- - method: hello -- -- -- -- -- 5, access method with multiple parameters and use -- -- -- -- -- frank xu lei 18 -- -- -- -- -- -- -- -- the sixth. Get the private method and use ----Copy the code