Java dynamic Proxy and Cglib dynamic Proxy sample sharing _java

Source: Internet
Author: User
Tags reflection stub throwable

Java dynamic proxy classes can be divided into two types.

Static agents: Created by a programmer or by a specific tool, the source code is automatically generated, and then compiled. Before the program runs, the. class file for the proxy class already exists.

Dynamic Agent: When the program is running, it is created dynamically by using the reflection mechanism.


First, we have a Java Dynamic proxy demo.

Now we have a simple business interface saying, as follows:

Copy Code code as follows:

Package TESTAOP;
public interface Saying {
public void SayHello (String name);
public void Talking (String name);
}

A simple implementation class Sayingimpl, as follows:

Copy Code code as follows:

Package TESTAOP;
public class Sayingimpl implements saying {
@Override
public void SayHello (String name) {
TODO auto-generated Method Stub
SYSTEM.OUT.PRINTLN (name + ": Hello, everyone!") ");
}
@Override
public void Talking (String name) {
TODO auto-generated Method Stub
SYSTEM.OUT.PRINTLN (name + ": I mean, we should strive to build a harmonious society!") ");
}
}

What we are going to achieve is dynamic implant processing before and after SayHello and talking respectively.

JDK dynamic proxies are mainly used in the two classes in the Java.lang.reflect package: Proxy and Invocationhandler.

Invocationhandler is an interface that, by implementing the interface, defines crosscutting logic and invokes the code of the target class through the reflection mechanism, and dynamically weaves crosscutting logic and business logic together.

Proxy uses Invocationhandler dynamic to create an instance that conforms to an interface and generates a proxy object for the target class.

As follows, we create a Invocationhandler instance:

Copy Code code as follows:

Package TESTAOP;

Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;

public class Myinvocationhandler implements Invocationhandler {

Private Object target;
Myinvocationhandler (Object target) {
This.target = target;
}
@Override
public object invoke (object proxy, Method method, object[] args)
Throws Throwable {
Before the target method executes
System.out.println ("——————————————————————————");
System.out.println ("The next one, please speak on the stage!") ");
Target method call
Object obj = Method.invoke (target, args);
Target method after execution
System.out.println ("Applause and encouragement!") ");
return obj;
}
}

Here is the test:

Copy Code code as follows:

Package TESTAOP;
Import Java.lang.reflect.Proxy;
public class Jdkproxytest {

public static void Main (string[] args) {
Target business class that you want to be represented
Saying target = new Sayingimpl ();
Weave the target class and the Crosscutting class together
Myinvocationhandler handler = new Myinvocationhandler (target);
To create a proxy instance
Saying proxy = (saying) proxy.newproxyinstance (
Target.getclass (). getClassLoader (),//class loader for the target class
Target.getclass (). Getinterfaces (),//interface to the target class
handler);//Crosscutting class
Proxy.sayhello ("Xiaoming");
Proxy.talking ("Xiaoli");
}
}

The operating conditions are as follows:

Copy Code code as follows:

——————————————————————————
The next one, please speak on the stage!
Xiao Ming: Hello, everyone!
Applause, Cheers!
——————————————————————————
The next one, please speak on the stage!
Xiaoli: I mean, we must strive to build a harmonious society!
Applause, Cheers!

A significant limitation of using JDK dynamic proxies is that it requires the target class to implement the interface of the corresponding method, which can only create proxy instances for the interface. As we can see in the Newproxyinstance method of the proxy in the test class above, the second parameter of the method is the interface of the target class. If the class does not implement an interface, it depends on the cglib dynamic proxy.

Using very low-level bytecode technology, Cglib can create a subclass of a class and use method-blocking techniques in subclasses to intercept calls to all parent-class methods and to embed crosscutting logic.

Second, we carry on the Cglib dynamic proxy demonstration.

First we need to guide the bag, I use the bag is Cglib-nodep-2.1_3.jar.

We first create a proxy creator Cglibproxy:

Copy Code code as follows:

Package testaop.cglib;
Import Java.lang.reflect.Method;
Import Net.sf.cglib.proxy.Enhancer;
Import Net.sf.cglib.proxy.MethodInterceptor;
Import Net.sf.cglib.proxy.MethodProxy;

public class Cglibproxy implements methodinterceptor{

Enhancer enhancer = new enhancer ();
Public Object GetProxy (Class clazz) {
Set up subclasses that need to be created
Enhancer.setsuperclass (Clazz);
Enhancer.setcallback (this);
Dynamic creation of subclass instances via bytecode technology
return Enhancer.create ();
}
@Override
public object intercept (object obj, Method method, object[] args,
Methodproxy proxy) throws Throwable {
TODO auto-generated Method Stub
System.out.println ("——————————————————————————");
System.out.println ("The next one, please speak on the stage!") ");
Target method call
Object result = Proxy.invokesuper (obj, args);
Target method after execution
System.out.println ("Applause and encouragement!") ");
return result;
}
}

Then test:

Copy Code code as follows:

Package testaop.cglib;
Import testaop.saying;
Import Testaop.sayingimpl;
public class Cglibproxytest {

public static void Main (string[] args) {
Cglibproxy proxy = new Cglibproxy ();
To create a proxy class by dynamically generating subclasses
Saying target = (saying) proxy.getproxy (Sayingimpl.class);
Target.sayhello ("Xiaoming");
Target.talking ("Xiaoli");
}
}

The result is no different from the JDK dynamic proxy.

Both JDK dynamic proxies and Cglib dynamic proxies are run-time enhancements that are enhanced by embedding crosscutting code into the proxy class. In contrast to this, ASPECTJ is able to enhance the crosscutting code implantation at compile time through a special compiler, which is more advantageous at runtime because the JDK dynamic agents and cglib dynamic agents need to be enhanced every time they run.

Related Article

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.