Senior Java - reflection

1. How to create an instance of the Class

1.1 Process: After the source file after compilation (javac.exe), to give one or more .class files. After running .class file (java.exe) this step, we need to load the class (by the JVM class loader), loaded into memory cache. .class file is placed in the cache for each instance of the Class.

1.2 Class of an object, corresponding to a runtime class. The equivalent of a run-time class itself acts as an instance of a Class of.

1.3 java.lang.Class is a reflection of the source. The next classes are involved in the reflection java.lang.reflect subpacket. Such as: Field Method Constructor Type Pacakage ..

  When calling getMethods () by way of example in Class -> Method, getConstructors () -> Constructor

Examples 1.4 Method of Class (the first three)

        // 1. Call the runtime class itself .class attribute 
        Class clazz1 = the Person. Class ; 
        System.out.println (clazz1.getName ()); 
        
        Class clazz2 . = String class ; 
        System.out.println (clazz2.getName ( )); 
        
        // 2. Get the object by runtime class is 
        the Person P = new new the Person (); 
        class clazz3 = p.getClass (); 
        System.out.println (clazz3.getName ()); 
        
        // 3. by class static method to obtain. in this way, taste, dynamic reflection. 
        ClassName = String "com.it.java.Person" ;         
        Class clazz4 = Class.forName (className);
 //        clazz4.newInstance();
        System.out.println(clazz4.getName());
        
        //4.(了解)通过类的加载器
        ClassLoader classLoader = this.getClass().getClassLoader();
        Class clazz5 = classLoader.loadClass(className);
        System.out.println(clazz5.getName());
        
        System.out.println(clazz1 == clazz3);//true
        System.out.println(clazz1 == clazz4);//true
        System.out.println(clazz1 == clazz5);//true

2. With the example of what can be done? Application One: You can create an object corresponding runtime class

    // Get the object runtime class: A method 
    @Test
     public  void test1 () throws Exception { 
        Class clazz = the Class.forName ( "com.it.review.Animal" ); 
        Object obj = clazz.newInstance (); 
        Animal A = (Animal) obj; 
        System.out.println (A); 
    }
    // call the constructor specifies the object to create runtime class 
    @Test
     public  void test2 () throws Exception { 
        Class clazz = Animal. Class ; 
        the Constructor cons = clazz.getDeclaredConstructor (. String class , int . Class ); 
        cons.setAccessible ( to true ); 
        Animal A = (Animal) cons.newInstance ( "Tom", 10 ); 
        System.out.println (A); 
    }

3. With the strength of what can be done? Application 2: Full obtain corresponding class runtime class structure: properties, methods, constructors, package, parent classes, interfaces, generic, annotation, abnormal internal class.

Such as: Method [] m1 = clazz.getMethods (): Get the privilege corresponding to the runtime class declared as public methods (including the parent class declared public)

  Method [] m2 = clazz.getDeclaredMethods (): Get all the runtime class corresponding methods declared (any permissions ① ② modifiers can be acquired free of the parent class)

4. With Class instance, what can be done? Applications 3: calling runtime class corresponding to the assigned structure (a specified property, method, constructor).

    // call specifies attributes 
    @Test
     public  void Test3 () throws Exception { 
        Class clazz = the Class.forName ( "com.it.review.Animal" ); 
        Object obj = clazz.newInstance (); 
        Animal A = (Animal) obj;
         // can call to a non-public properties (properties more calls to the public, limiting itself does not include the parent class) 
        Field, F1 = clazz.getDeclaredField ( "name" ); 
        f1.setAccessible ( to true ); 
        f1.set (a, " Jerry " );
         // call public property 
        Field, F2 = clazz.getField (" Age " ); 
        f2.set (a,9);
        System.out.println(f2.get(a));
        System.out.println(a);
        //调用static的属性
        Field f3 = clazz.getDeclaredField("desc");
        System.out.println(f3.get(null));
    }
    // call the specified method 
    @Test
     public  void Test4 () throws Exception { 
        Class clazz = the Class.forName ( "com.atguigu.review.Animal" ); 
        Object obj = clazz.newInstance (); 
        Animal A = (Animal) obj ; 
       
        // can invoke a non-public methods (including the methods of public) 
        method, clazz.getDeclaredMethod = M1 ( "getAge" ); 
        m1.setAccessible ( to true );
         int Age = (Integer) m1.invoke (a); 
        the System.out .println (Age); 
        // call the public methods 
        method m2 = clazz.getMethod ( "show" , String.class);
        Object returnVal = m2.invoke(a,"金毛");
        System.out.println(returnVal);
        //调用static的方法
        Method m3 = clazz.getDeclaredMethod("info");
        m3.setAccessible(true);
//        m3.invoke(Animal.class);
        m3.invoke(null);
    }

The dynamic proxy - Application of reflection. Experience dynamic reflection.

 Proxy design pattern principles:

  Using a proxy packaged objects, the original object is then substituted with the proxy object. Any call to the original object must be through a proxy, the proxy object to decide whether and when to go to the original object method calls

Static Agent: required to be proxy class and a corresponding proxy class implements a set of interfaces; when the object method call override proxy class interfaces, the call is actually performed is the same manner as the proxy class.

Dynamic Agent: the program is running, according to the proxy class and its interface is implemented, dynamically create a proxy class. When the agent calls the abstract methods of the class, it initiates a call to the proxy class is the same method.

Involves technical points: ① the InvocationHandler provide an implementation class that implements the interface and override its invoke () method

       ②Proxy.newInstance (.. Obj.getClass () getClassLoader (), obj.getClass () getInterfaces (), h); // NOTE: obj: the proxy object; h: InvocationHandler implementation class implements the interface.

 

// dynamic proxies, experience a reflection critical dynamic language 
interface the Subject {
     void Action (); 
} 
// the proxy class 
class RealSubject the implements the Subject { 

    public  void Action () { 
        System.out.println ( "... RealSubject ... Action " ); 
    } 
} 

class MyInvocationHandler the implements of InvocationHandler { 
    Object obj; // achieve the objects declared by the interface proxy class 

    // ① to the proxy object to instantiate a proxy object is returned ② class 
    public Object getDynamicProxy ( obj Object) {
         the this .OBJ = obj;
         returnThe Proxy.newProxyInstance (obj.getClass () getClassLoader (), obj.getClass () The getInterfaces (),.. The this ); 
    } 

    // when calling a proxy object of the class to be rewritten initiating by the method, will be converted to invoke method call as a 
    public Object invoke (Object Proxy, method, method, Object [] args) throws the Throwable { 
        Object returnVal = Method.invoke (obj, args);
         return returnVal; 
    } 
} 

public  class TestProxy { 
    @Test 
    public  void Test01 () {
         // 1. Create the proxy object 
        RealSubject RealSubject = new new RealSubject ();
         //2. Create Object class interface implemented InvocationHandler 
        MyInvocationHandler myInvocationHandler = new new MyInvocationHandler ();
         // 3. obtaining dynamic proxy 
        Object Proxy = myInvocationHandler.getDynamicProxy (RealSubject);
         // must be converted to proxy class interface is implemented: the source -Proxy .newProxyInstance: using the interface reflection corresponding constructor 
        the Subject Subject = (the Subject) Proxy; 
        subject.action (); // go to invoke InvocationHandler interface implementation class () method call 
    }

 

Guess you like

Origin www.cnblogs.com/gzhcsu/p/11797666.html