What is reflection
Reflection means that all properties and methods of any class can be known in the running state; And any method of any object can be called; This function of dynamically obtaining information and dynamically calling object methods is called reflection mechanism.
Where is the reflection mechanism used?
-
In JDBC, the database driver is dynamically loaded by reflection.
-
The service method of Sevlet is called by reflection in the Web server.
-
Eclispe and other development tools use reflection to dynamically analyze the type and structure of objects and dynamically prompt the attributes and methods of objects.
-
Many frameworks use reflection mechanism, inject attributes and call methods, such as Spring.
Advantages and disadvantages of reflection mechanism?
- Advantages: it can be executed dynamically. During operation, it can dynamically execute methods and access properties according to business functions, giving full play to the flexibility of java.
- Disadvantages: it has an impact on performance. Such operations are always slower than direct execution of java code.
Function of reflection
- Classes can be dynamically configured and loaded through configuration files to realize the decoupling between classes and modules mentioned in software engineering theory. The most classic application of reflection is the spring framework.
What is a dynamic agent? What are the applications?
-
Dynamic proxy is a dynamically generated proxy class at run time.
-
The applications of dynamic proxy include Spring AOP data query, back-end mock and rpc of test framework, Java annotation object acquisition, etc.
How to implement dynamic proxy?
-
JDK native dynamic proxy and cglib dynamic proxy.
-
JDK native dynamic proxy is implemented based on interface, while cglib is implemented based on subclasses that inherit the current class.
How to use Java reflection?
- Create an object with a fully qualified class name
Class.forName("full class name"); For example: com mysql. jdbc. The driver class has been loaded into the jvm and the initialization of the class has been completed
Class name class; Get class <? > CLZ object
Object getClass(); - Get the constructor object and create an object through the constructor new
Clazz.getConstructor([String.class]);
Con.newInstance([parameter]);
Create an instance object through the class object (equivalent to the new class name () parameterless constructor)
Cls.newInstance(); - Get a property object through the class object
Field c=cls.getFields(): get all the public fields of a class, including the fields in the parent class.
Field c=cls. Getdeclaraedfields(): get all declared fields of a class, including public, private and protected, but excluding the declared fields of the parent class - Get a method object from the class object
Cls.getMethod("method name", class... parameaType); (public only)
Cls.getDeclareMethod("method name"); (get any decorated method, cannot execute private)
M.setAccessible(true); (make private methods executable)
Let the method execute
1). Method.invoke(obj instance object, obj variable parameter)----- (it has a return value)
Code example
The first method is implemented through the full path of the class
Create a new Person class to be reflected
package com.test.Reflect; public class Person { private String name; private String gender; private int age; private Person() { // } public Person(String name, String gender, int age) { super(); this.name = name; this.gender = gender; this.age = age; } //getter, and setter methods private String getName() { return name; } private void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString(){ return "full name:"+name+"Age: "+age; } }
package com.test.Reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import javax.swing.JOptionPane; /** * Get the member methods and properties of the class by entering the full path of the class * Declared Get everything, private and public * 1.Gets the Class object of the access Class * 2.Call the method of the Class object to return the method and property information of the access Class **/ public class ReflectDemo1 { /* * Construction method */ public ReflectDemo1(){ //Full path of user input class //Using String components String classpsth=JOptionPane.showInputDialog(null,"Enter the full path of the class"); //Use Class The forname method returns the Class object of the input Class according to the full path of the Class try { Class cla = Class.forName(classpsth); //Use the self audit of the cla of the Class object to return the method object set Method [] method=cla.getDeclaredMethods(); //Return all methods System.out.println("========Get method information============"); for (Method meth : method) { //Traverse the method array and output method information System.out.println(meth.toString()); } System.out.println("========End of fetching method information============"); //Get the attribute, use the self audit of the cla of the Class object, and return the collection of member attribute objects Field [] field=cla.getDeclaredFields(); System.out.println("========Get member property information============"); for (Field f : field) { System.out.println(f.toString()); } System.out.println("========End of getting member property information============"); //Get the attribute, use the self-examination of the cla of the Class object, and return the constructor collection Constructor [] constructor=cla.getDeclaredConstructors(); System.out.println("========Get member construction method information============"); for (Constructor constru : constructor) { System.out.println(constru.toString()); } System.out.println("========End of getting member construction method information============"); } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.println("Path input error!"); } } }
Test class
package com.test.Reflect; /** * Test class * @author Admin * */ public class TestReflection { public static void main(String[] args) { ReflectDemo1 rd=new ReflectDemo1(); } }
Output results
After execution, a simple pop-up window will be used to enter the full path of the class: com test. Reflect. Person
The output result is:
========Get method information============ public java.lang.String com.test.Reflect.Person.toString() private java.lang.String com.test.Reflect.Person.getName() private void com.test.Reflect.Person.setName(java.lang.String) public java.lang.String com.test.Reflect.Person.getGender() public void com.test.Reflect.Person.setGender(java.lang.String) public void com.test.Reflect.Person.setAge(int) public int com.test.Reflect.Person.getAge() ========End of fetching method information============ ========Get member property information============ private java.lang.String com.test.Reflect.Person.name private java.lang.String com.test.Reflect.Person.gender private int com.test.Reflect.Person.age ========End of getting member property information============ ========Get member construction method information============ private com.test.Reflect.Person() public com.test.Reflect.Person(java.lang.String,java.lang.String,int) ========End of getting member construction method information============
The second method is getClass() of the object
First, use the Person class above, but change the attribute of the constructor to default
public class Person { private String name; private String gender; private int age; Person() { // } public Person(String name, String gender, int age) { super(); this.name = name; this.gender = gender; this.age = age; } //getter, and setter methods private String getName() { return name; } private void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString(){ return "full name:"+name+"Age: "+age; }
The ReflectDemo class is basically unchanged, but the value transfer method of cla has changed to Class cla=p.getClass();
public ReflectDemo2(Person p){ Class cla=p.getClass(); //Use the self audit of the cla of the Class object to return the method object set Method [] method=cla.getDeclaredMethods(); //Return all methods System.out.println("========Get method information============"); for (Method meth : method) { //Traverse the method array and output method information System.out.println(meth.toString()); } System.out.println("========End of fetching method information============"); //Get the attribute, use the self audit of the cla of the Class object, and return the collection of member attribute objects Field [] field=cla.getDeclaredFields(); System.out.println("========Get member property information============"); for (Field f : field) { System.out.println(f.toString()); } System.out.println("========End of getting member property information============"); //Get the attribute, use the self-examination of the cla of the Class object, and return the constructor collection Constructor [] constructor=cla.getDeclaredConstructors(); System.out.println("========Get member construction method information============"); for (Constructor constru : constructor) { System.out.println(constru.toString()); } System.out.println("========End of getting member construction method information============"); }
test
public class TestReflection { public static void main(String[] args) { // ReflectDemo1 rd=new ReflectDemo1(); Person person = new Person(); ReflectDemo2 reflectDemo2 = new ReflectDemo2(person); } }
The result is the same as the output above
========Get method information============ public java.lang.String com.test.Reflect.Person.toString() private java.lang.String com.test.Reflect.Person.getName() private void com.test.Reflect.Person.setName(java.lang.String) public java.lang.String com.test.Reflect.Person.getGender() public void com.test.Reflect.Person.setGender(java.lang.String) public int com.test.Reflect.Person.getAge() public void com.test.Reflect.Person.setAge(int) ========End of fetching method information============ ========Get member property information============ private java.lang.String com.test.Reflect.Person.name private java.lang.String com.test.Reflect.Person.gender private int com.test.Reflect.Person.age ========End of getting member property information============ ========Get member construction method information============ com.test.Reflect.Person() public com.test.Reflect.Person(java.lang.String,java.lang.String,int) ========End of getting member construction method information============
The third way is to use it directly class attribute
Just add the class name directly If class is assigned to Class cla, you can continue to output class information as above. I won't repeat it here.
Class cla=Person.class;