Follow Gongge to sort out the knowledge points of java: reflection and proxy (17)

Keywords: Java Attribute

What is the reflex mechanism?
The reflection mechanism is that in the running state, for any class, all the attributes and methods of this class can be known.
For any object, one of its methods and attributes can be invoked, the information obtained dynamically, and
The function of dynamically invoking methods of objects is called the reflection mechanism of java language.

What can the reflex mechanism do?
Reflection mechanism mainly provides the following functions
Judging the class of any object at runtime
Constructing objects of any class at runtime
Judging the attributes and methods of any class at runtime
Call an object's method at runtime
_Generating dynamic proxy

Get the complete package name and class name through an object

package com.hzg;
public class TestReflect {
    public static void main(String[] args) throws Exception {
        TestReflect testReflect = new TestReflect();
        System.out.println(testReflect.getClass().getName());
        // Result com.hzg.TestReflect
    }
}

Obtaining complete attributes and methods through an object

Class clazz = Person.class();
//1,Establish clazz Runtime classes of objects Person object
Person p = (Person)clazz.getInstance();
//2,Call specified properties at runtime by reflection
Filed f1 = clazz.getField("name");
f1.set(p,"LiudeHua");
//3,Call the specified method at runtime by reflection
Method m1 = clazz.getMethod("show",String.class);
m1.invoke(p,"CHN");

Note: Class is not a keyword class, Class is a class name, class is a keyword identifier is a class

Get instances of class es (three ways)
(1) Call the. class attribute of the runtime class itself
    Class clazz = Person.class;
(2) Object acquisition through runtime classes
    Person p = new Person();
    Class clazz = p.getClass();
(3) Obtain by static method of class
    Class clazz = Class.forName("com.hzg.TestReflect");

package com.hzg;
public class TestReflect {
    public static void main(String[] args) throws Exception {
        Class<?> class1 = null;
        Class<?> class2 = null;
        Class<?> class3 = null;
        // ① Static methods (generally in this form)
        class1 = Class.forName("com.hzg.TestReflect");
        // ② Object acquisition of runtime classes
        class2 = new TestReflect().getClass();
        // ③ Class itself.class attribute
        class3 = TestReflect.class;
        System.out.println("Class name   " + class1.getName());
        System.out.println("Class name   " + class2.getName());
        System.out.println("Class name   " + class3.getName());
    }
}    

Getting the parent class of an object and the interface to its implementation

 1 package com.hzg;
 2 import java.io.Serializable;
 3 public class TestReflect implements Serializable {
 4     private static final long serialVersionUID = -2862585049955236662L;
 5     public static void main(String[] args) throws Exception {
 6         Class<?> clazz = Class.forName("com.hzg.TestReflect");
 7         // Get the parent class
 8         Class<?> parentClass = clazz.getSuperclass();
 9         System.out.println("clazz The parent class is:" + parentClass.getName());
10         // clazz The parent class is: java.lang.Object
11         // Get all the interfaces
12         Class<?> intes[] = clazz.getInterfaces();
13         System.out.println("clazz The interfaces implemented are:");
14         for (int i = 0; i < intes.length; i++) {
15             System.out.println((i + 1) + ": " + intes[i].getName());
16         }
17     }
18 }

 

What can we do with the class instance?
(1) Objects that correspond to runtime classes can be created
(2) Obtaining corresponding operations is the complete class structure of a class: attributes, methods, constructors, packages, generics, annotations, exceptions, internal classes.
Method[] m1 = clazz.getMethods(): Get all public methods of classes and parent classes
Method [] M1 = clazz. getDeclared Methods (): All modifier methods
However, there is no parent class, only all modifier methods in this class
(3) Call runs are the structures specified in the class (properties, methods, constructors)
Get the specified attribute: Field name = clazz.getField("name");
Set the specified public property: name.set(p,"hzg");
Set the specified private property:
      Field name = clazz.geDeclaredtField("name");
      name.setAccessible(true);
      name.set(p,"hzg");
Get the specified method: Method m1 = clazz.getMethod("show");
Call the specified method:
Object obj = m1.invoke(p); the return type is the return type of the method

Call static methods: m1.invoke(Person.class);
Call the specified method with parameters:
      Method m1 = clazz.getDeclatedMethod("show1",String.class);
      Object obj = m1.invoke(p,"hzg");

Call the constructor: Constructor con = clazz. getDeclared Constructor ();
Call a parametric constructor, consistent with the parametric method

Application of Java Reflection - Agent

1. Static proxy (static proxy based on interface polymorphism)

 1 interface ClothFactory{
 2   void productCloth();
 3 }
 4 //Proxy class
 5 class NikeClothFactory implements ClothFactory{
 6   @Override
 7   public void productCloth(){
 8     sysytem.out.printLn("NIKE The factory produces a batch of clothes.");
 9   }
10 }
11 //proxy class
12 class ProxyFactory implements ClothFactory{
13   ClothFactory cf;
14   public ProxyFactory(ClothFactory cf){
15     this.cf = cf;
16   }
17   @Override
18   public void productCloth(){
19     sysytem.out.printLn("Agent class starts to execute and charges 1000 agent fees.");
20     cf.productCloth();
21   }
22 }
23 
24 public class Test{
25   public static void main(String[] args){
26     //① Create a proxy object
27     NikeClothFactory nike = new NikeClothFactory ();
28     //② Create a proxy class object
29     ProxyFactory proxy = new ProxyFactory(nike);
30     //③ Method of calling proxy class object
31     proxy.productCloth();
32   }
33 }

Static proxy summary:
(1) Both proxy and proxy classes implement the same interface.
(2) Both the proxy class and the proxy class implement the methods in the interface.


2. Dynamic Agent (Dynamic Agent Based on Reflection Implementation)

 1 interface ClothFactory{
 2   void productCloth();
 3 }
 4 //Proxy class
 5 class NikeClothFactory inplements ClothFactory{
 6   @Override
 7   public void productCloth(){
 8     sysytem.out.printLn("NIKE The factory produces a batch of clothes.");
 9   }
10 }
11 //①Must be achieved InvocationHandler Interface
12 class MyInvocationHandler implements InvocationHandler{
13   //② Proxy classes that declare interfaces
14   Object obj;
15   //③ Create a method instantiation proxy class
16   public Object bind(Object obj){
17     this.obj = obj;
18     return Proxy.newProxyInstance(
19     obj.getClass().geyClassLoder(),
20     obj.getClass().getInterfaces(),this);
21   }
22   //④ Implementation interface InvacationHandler Method
23   // This method implementation: When the object method of the proxy class is invoked, it is converted to it for invocation.
24   @Override
25   public Object invoke(Object proxy,Method method,Object[] args){
26     Object returnVal = method.invoke(obj,args);
27     return returnVal();
28   }
29 }
30 //Call to implement it
31 public class Test{
32   public static void main(String[] args){
33     //① The old rule: Create a proxy object
34     NikeClothFactory nike = new NikeClothFactory ();
35     //②The old rule: Create a proxy class object
36     MyInvocationHandler hander = new MyinvocationHanlder();
37     ClothFactory proxyCloth = (ClothFactory)hander.bind(nike);
38     //③ Old Rule: Method for Calling Proxy Class Objects
39     proxyCloth .productCloth();
40   }
41 }

Posted by wolves on Sat, 06 Jul 2019 14:18:03 -0700