Java reflection and dynamic agent detailed

Source: Internet
Author: User

in spring, the principle of AOP is the dynamic proxy mechanism of Java, and the dynamic proxy is related to reflection, so we review the knowledge of reflection and dynamic agent. Reflex

The JVM uses the class loader to load the. class file into the JVM's memory. The binary byte stream of the class file is converted to the RUN-TIME data structure of the method area, with information such as the version of Class object, fields, methods, interfaces, and so on, in the heap, which generates each class-unique type Object class object as access to the method area class information. Mouth.

 The Java reflection mechanism allows us to get the class object of any classes in the runtime, to get the interface, method, field, etc. of the class in the method area, or to instantiate the object at run time. instantiate the Class object:

class<?> demo1 = Class.forName ("Reflect.name");//Instantiate Class object
class<?> = new Demo () by fully qualified name. GetInstance ();
class<?> Demo3 = Demo.class;
Gets the full package name and class name from an instance object:

Demo1.getclass (). GetName (); Instantiate an instance of a class through a class object

A the parameterless constructor instantiation: Person
 p = (person) demo1.newinstance ();
b) Parametric constructor instantiation, first get constructor:
constructor<?> cons[] = demo.getconstructors ();
person P1 = (person) cons[1].newinstance ("Rollen"); Returns the interface of a class:
class<?> demo = Class.forName ("Reflect.person" );
Save all the interfaces
class<?> intes[] = demo.getinterfaces ();
Intes[i].getname ();
To get the parent class of another class:
class<?> temp = Demo.getsuperclass ();
Temp.getname ();
Get constructors for other classes:
constructor<?> cons[] = demo.getconstructors ();
To Get Properties (fields) for other classes:

Properties of this class (for example: public string name)
field[] field = Demo.getdeclaredfields ();
Permission modifiers
int mo = Field[i].getmodifiers ();
String priv = modifier.tostring (MO);
Property type
Class

The Saychina method in the person class is invoked to methods
= Demo.getmethod ("Saychina");
Method.invoke (Demo.newinstance ());

Invoke the SayHello method in the person class to approach methods
= Demo.getmethod ("SayHello", string.class,int.class);
Method.invoke (Demo.newinstance (), "Rollen", 20);
To manipulate properties by reflection:
class<?> demo = Class.forName ("Reflect.person");
Object obj = demo.newinstance ();
Field field = Demo.getdeclaredfield ("Sex");
Field.setaccessible (true);
Field.set (obj, "male");/set sex property to "male"
Dynamic agent mechanism

In dynamic proxy mechanism, there is an important class proxy and an important interface Invocationhandler. Remember three concepts first: 1. Dynamic proxy class, each dynamic proxy class is a invocationhandler subclass. 2. Proxy object, by Proxy.newproxyinstance (...) The proxy object that is created, and each proxy object associates a dynamic proxy class instance, which is converted to a call to the Invoke method of the handler dynamic proxy class when the proxy object invokes the real object method. 3. Real object, we want to proxy the object.

after introducing the concept of dynamic proxy class, proxy object and real object, we have an example to really understand how dynamic proxy mode is implemented:

first define a subject interface, define the rent () method, and the Hello () method:

package invocation;

/**
 * Created by Kang on 17/9/28.
 * * Public
interface Subject {public

    void rent ();

    public void Hello (String hello);

defines a realsubject interface, which is the real object, which is the proxy object:

package invocation;

/**
 * Created by Kang on 17/9/28.
 *
///Real Object Public
class Realsubject implements Subject {

    @Override public
    void rent () {
        System.out.println ("I want to rent my house!");
    }

    @Override public
    void Hello (String hello) {
        System.out.println ("Hello  " +hello);
    }

Define a dynamic proxy class, each dynamic proxy class needs to implement the Invocationhandler interface, in the dynamic proxy class to pass in the real object, then each proxy object binding a dynamic proxy class instance, and each dynamic proxy class has an Invoke method.

Package invocation;
Import Java.lang.reflect.InvocationHandler;

Import Java.lang.reflect.Method;
 /** * Created by Kang on 17/9/28. *///Dynamic proxy class Myinvocationhandler is a subclass of Invocationhandler and must implement the Invoke method public class Dynamicproxy implements

    Invocationhandler {//The real object to be represented is private objects;
    Assigns the real object to the proxy the public Dynamicproxy (object) {This.object = object; /** * * @param proxy refers to the creation of the Agent object * @param method means the object of one of the methods of the real object we want to proxy * @param args refers to the true

        The parameters of a method of the image * * @Override public object Invoke (Object proxy, methods method, object[] args) throws Throwable {

        Add some of our own operations System.out.println ("before Rent House") before acting on real objects;

        System.out.println ("Method:" + method);

        When the proxy object invokes the method of the real object, it automatically jumps to the Invoke method of the dynamic proxy class, the Invocationhandler subclass, to invoke the Method.invoke (Object,args);

        Agent real Object After adding some operations System.out.println ("After the Rent House");
    return null;
 }
}

View the client class:

Package invocation;
Import Java.lang.reflect.InvocationHandler;

Import Java.lang.reflect.Proxy;
 /** * Created by Kang on 17/9/28.
        * * Public class Client {public static void main (string[] args) {//subject is a real object, handler is a dynamic proxy class, passing in a real object to a dynamic proxy class
        Subject realsubject = new Realsubject ();


        Invocationhandler handler = new Dynamicproxy (realsubject);
         /** * Create a proxy object through the Newproxyinstance method of proxy * 1. The first parameter, Handler.getclass (), getClassLoader () indicates that the proxy object is loaded with the class loader of the dynamic proxy class
         * 2. The second parameter Realsubject.getclass (). Getinterfaces () is passed into the interface of the real object, so the proxy object can also invoke the interface, using the method of the real object.
         * 3. The third object handler lets the proxy object relate to the dynamic proxy class, and when the proxy object invokes the method of the real object, it can automatically jump to the Invoke method that executes the handler. * */Subject Subject = (Subject) proxy.newproxyinstance (Handler.getclass (). Getclassloade

        R (), Realsubject.getclass (). Getinterfaces (), handler);
        System.out.println (Subject.getclass (). GetName ());
        Subject.rent ();

    Subject.hello ("Nihao");
 }

}

Let's take a look at the console output first:

Com.sun.proxy. $Proxy 0
before rent house
method:public abstract void Invocation.Subject.rent ()
I want to Rent my house!
After rent house
before rent house
method:public abstract void Invocation.Subject.hello (java.lang.String)
Hello  nihao after
rent house


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.