Java Dynamic Agents (JDK and Cglib)

Source: Internet
Author: User
Tags throwable

Java Dynamic Agents (JDK and Cglib)

Dynamic Agent for Java
Proxy mode:
Proxy mode is a common Java design pattern, his characteristic is that the proxy class and the delegate class have the same interface, the proxy class is mainly responsible for the delegate class preprocessing messages, filtering messages, forwarding messages to the delegate class, and post-processing messages. There is usually an association between the proxy class and the delegate class, and the object of a proxy class is associated with an object of a delegate class, and the object of the proxy class does not actually implement the service, but instead provides a specific service by invoking the related method of the object of the delegate class.
The proxy class can be divided into two types according to the agent's creation period.
Static proxy: The source code is generated automatically by the programmer or a specific tool, and then compiled. Before the program runs, the. class file for the proxy classes already exists.
Dynamic Agent: When the program is running, it is created dynamically using the reflection mechanism.


First, the JDK dynamic agent:

Direct use of JDK-API;

Proxy objects can only be created for classes that implement an interface (objects are created through an interface).

/**

*① Create a proxy class Jdkdynamicproxy implement Invocationhandler interface

*② implementing an Invoke method in an interface

*③ defines an object-type property in the class that is used to pass the Proxied object

*④ provides a constructor with type Object

*⑤ creates a method GetProxy returns an object that is the proxy object for the Proxied object

*/


List of programs:
1.TestInterface interface

Package Com.softeem.dynamicproxy;public interface TestInterface {public void test01 ();

2.TestInterface Implementation Interface

Package Com.softeem.dynamicproxy;public class Testimplement implements TestInterface {@Overridepublic void test01 () { System.out.println ("This is the JDK Dynamic Agent test Method");}}

3.JDK Dynamic Agent

package com.softeem.dynamicproxy;import java.lang.reflect.invocationhandler;import  java.lang.reflect.method;import java.lang.reflect.proxy;/** *  Direct use of jdk-api *  Proxy objects can only be created for classes that implement an interface (create objects through interfaces)  * ① Create a proxy class Jdkdynamicproxy implement Invocationhandler interface  *  ② implements the Invoke method in an interface  * ③ defines an object-type property in the class that is used to pass the Proxied object  * ④ provides a constructor with type Object  *  ⑤ creates a method GetProxy returns an object that is the proxy object for the Proxied object  */public class JDKDynamicProxy implements  Invocationhandler {private object obj;public jdkdynamicproxy (Object obj)  { This.obj = obj;} Gets the proxy object Public object getproxy () {object proxyobj = null;proxyobj =  Proxy.newproxyinstance (Obj.getclass (). getClassLoader (),  obj.getclass (). Getinterfaces (),  this);// To bind the interface (this is a flaw, cglib compensates for this flaw) return proxyobj;} @Overridepublic  object invoke (Object proxy, method method, object[] args) ThrowS throwable {system.out.println ("-------"); Object returnobj = method.invoke (obj,  args); System.out.println ("<><><><>"); return returnobj;}}

4.Test Test class

Package Com.softeem.dynamicproxy;public class Test {public static void main (string[] args) {testimplement ti = new Testimp Lement ();//create proxy objects for Ti objects object obj = new Jdkdynamicproxy (TI). GetProxy ();//obj objects that exist only in memory System.out.println ( Obj.getclass ());//Because the JDK dynamic agent is a proxy object created through an interface testinterface tif = (testinterface) obj;//testinterface tif2 = new Testimplement (); A parent class reference to a Subclass object (polymorphic), cannot call a subclass-specific method, can only invoke a class in an abstract method//When invoking a method through a proxy object, is actually invoking the Invoke method in the class proxy class tif.test01 ();}}


Second,cglib dynamic Agent

Use to class third-party jar packages: Cdlib.jar

Proxy objects cannot be created for the final class (proxy objects are created from subclasses)

/**

*① Create a proxy class Cglibdynamicproxy implement Methodinterceptor interface

*② implementing the Intercept method

*③ defines an object-type property in the class that is used to pass the Proxied object

*④ provides a constructor with type Object

*⑤ creates a method GetProxy returns an object that is the proxy object for the Proxied object

*/

List of programs

1.cglib Dynamic proxy class Cglibdynamicproxy

package com.softeem.dynamicproxy;import java.lang.reflect.method;import  net.sf.cglib.proxy.enhancer;import net.sf.cglib.proxy.methodinterceptor;import  net.sf.cglib.proxy.methodproxy;/** *  use to class third-party jar:cdlib.jar *  cannot create proxy objects for the final class (proxy objects are created from subclasses)  * ① Create a proxy class Cglibdynamicproxy implement Methodinterceptor interface  * ② Implement intercept method  *  ③ defines an object-type property in the class that is used to pass the Proxied object  * ④ provides a constructor with type Object  * ⑤ creates a method GetProxy returns an object that is the proxy object of the Proxied object  */public class CGLibDynamicProxy implements MethodInterceptor {private  Object obj;public cglibdynamicproxy (Object obj)  {this.obj = obj;} Public object getproxy () {//Create proxy Object Enhancer en = new enhancer () for it by creating a subclass of the Proxied object; En.setsuperclass (Obj.getclass ()); En.setcallback (this);//callback Return en.create ();} @Overridepublic  object intercept (OBJECT&NBSP;ARG0,&NBSP;METHOD&NBSP;METHOD,&NBSP;OBJECT[]&NBSP;ARG2, MethodPROXY&NBSP;ARG3)  throws throwable {system.out.println ("-------"); object returnobj =  method.invoke (OBJ,&NBSP;ARG2); System.out.println ("<<><><><><>>"); return returnobj;}}

2.CGLibTest Test class

Package Com.softeem.dynamicproxy;public class Cglibtest {public static void main (string[] args) {testimplement ti = new Te Stimplement (); Cglibdynamicproxy CGDP = new Cglibdynamicproxy (TI);//Create a proxy object for ti objobject obj = cgdp.getproxy ();//proxy object created by creating a subclass of the Proxy object class So it can be said that the proxy object is directly strongly converted to the type of the proxied object testimplement t = (testimplement) obj;t.test01 ();}}


This article from "Black Foot Sanji" blog, declined reprint!

Java Dynamic Agents (JDK and Cglib)

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.