The most detailed agent to explain--JDK dynamic agent and Cglib agent

Source: Internet
Author: User
Tags throwable

1. Agency-related concepts

Agent mode

The agent mode of English is called proxy or surrogate, Chinese can be translated as "agent", the so-called agent, is a person or an institution on behalf of another person or another body to take action. In some cases, a customer does not want to or cannot directly refer to an object, and the proxy object can act as a mediator between the client and the target object

Abstract Theme Roles

Declares a common interface between real and agent topics, so that you can use a proxy theme wherever you can use a real theme

Agent Theme (proxy ) Role

The agent theme role contains a reference to the real topic, so that the real subject object can be manipulated at any time, and the agent theme role provides the same interface as the real-world theme, so that it can be used at any time to replace the real topic to control the reference to the real subject. Responsible for creating real subject objects (and deleting real subject objects) when needed; Agent roles usually perform an action before or after the client call is passed to the real topic, rather than simply passing the call to the real subject object.

Real Theme Roles

Defines the real object represented by the proxy role

Spring has two ways of acting:

1. If the target object implements several interfaces, spring uses the JDK's Java.lang.reflect.Proxy class proxy.

2. If the target object does not implement any interfaces, spring uses the Cglib library to generate a subclass of the target object.

2. Case study the similarities and differences of two kinds of agents

JDK Dynamic Proxy

Note: Writing the JDK proxy class refers to a proxy under the reflection package in Java Toolkit Lang, and does not require the introduction of other jar packs, but be careful not to fail the package; import Java.lang.reflect.Proxy; The target object implements several interfaces.

Two interface classes Saybyebye, Saygoodbye

Package www.csdn.spring.proxy.jdk;

Public interface Saybyebye {public void Saybyebye ();

} package www.csdn.spring.proxy.jdk;

Public interface Saygoodbye {public void Saygoodbye (String content);

The implementation class of these two interface classes saybyeimplement package www.csdn.spring.proxy.jdk; public class Saybyeimpl implements Saygoodbye,saybyebye {@Override public void Saygoodbye (String content) {SYSTEM.O
	Ut.println ("Say:" +content); @Override public void Saybyebye () {System.out.println say: bye.
	");

} JDK proxy class Jdkproxy package www.csdn.spring.proxy.jdk;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;

Import Java.lang.reflect.Proxy;

	public class Jdkproxy implements Invocationhandler {//Proxy target object private object target;
		The proxy object that created the target object, public object Createproxyinstance (object target) {//proxy object this.target = target; Create proxy object//1, Class loader/2 for proxy class, List of interfaces to be implemented by proxy class//3, call handler to assign method call return Proxy.newproxyinstance (Target.getclass (). Get ClassLoader (), Target.getclass (). Getinterfaces (), this);
	 /** * Proxy: proxy instance of target object, change proxy instance no matter how many times it is run class $Proxy 4;
	 * Method: For proxy instance to invoke the interface methods instance;
		 * Args: Method parameters */@Override public object Invoke (object proxy, methods method, object[] args) throws Throwable {/*
		* Test the meaning of the three parameters of the Invoke method * * SYSTEM.OUT.PRINTLN ("proxy:" +proxy.getclass ());
		System.out.println ("Method:" +method.getname ());
			if (args!=null&&args.length>0) {for (Object Obj:args) {System.out.println ("args:" +obj);
		}//Declaration return value Object returnvalue = null;
		Beforemethod ();
		returnvalue = Method.invoke (target, args);
		Aftermethod ();
	Return returnvalue;
	public void Beforemethod () {System.out.println ("operation before----method----");
	public void Aftermethod () {System.out.println (action after----method----);

The test class protest package www.csdn.spring.proxy.jdk;

Import Org.junit.Test;
	public class Proxytest {@Test public void Testsay () {//true theme role Saybyeimpl Saybyeimpl = new Saybyeimpl ();	
		* *//no use of Agent * Saybyeimpl.saygoodbye ("I Want a divorce.") 
		 ");
		 * Saybyeimpl.saybyebye (); *//Agent theme roles, where the same interface class implemented with the agent theme and the real theme is used to receive the agent theme created, that is, create a target class Saygoodbye Saygoodbye = (saygoodbye) new Jdkproxy (). Create
		Proxyinstance (Saybyeimpl);
	    Saybyebye Saybyebye = (saybyebye) new Jdkproxy (). Createproxyinstance (Saybyeimpl); Saygoodbye.saygoodbye ("I can't stand it, I want a divorce.")
	    ");
	    System.out.println ("00000000000000000000000000000000000000000000000");
	Saybyebye.saybyebye ();


 }

}


Cglib as an agent.

Cglib is a powerful, high-performance, high-quality code generation Class library. It can extend Java classes and implement Java interfaces at runtime.

Note: use Cglib as Agent, Java does not want the JDK dynamic proxy to encapsulate the corresponding class, he needs to import the jar package Asm-3.3.jar, Cglib-2.2.jar these two jar packages; the target object does not implement any interfaces

Target class SayHello

package Www.csdn.spring.proxy.cglib;

Publicclass SayHello {

publicvoid Say (String content) {

System.out.println ("say:" + content);

}

}

Cglib proxy class Cglibproxy

Package www.csdn.spring.proxy.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{private Object target;
		public object Createproxyinstance (object target) {this.target = target;
		Generate proxy Object Enhancer enhancer = new enhancer ();
		The parent class Enhancer.setsuperclass (This.target.getClass ()) that is used to set the proxy object;
		Set callback Enhancer.setcallback (this);
	Create proxy object return Enhancer.create (); /** * Proxy: an instance of the target object proxy; * Method: The target object invokes an instance of method of the parent class; * Args: Invokes the parent class method to pass the parameter * Methodproxy: Proxy methods to invoke the target method * * @Over
		Ride public Object intercept (object proxy, Method method, object[] args, Methodproxy methodproxy) throws Throwable {
		/* * Test the meaning of the four parameters of the Invoke method * * SYSTEM.OUT.PRINTLN ("proxy:" +proxy.getclass ());
		System.out.println ("Method:" +method.getname ());
		System.out.println ("Methodproxy:" +methodproxy.getsupername ()); if (args!=null&&args.length>0) {for (Object Obj:args) {System.out.println ("args:" +obj);
		}//Declaration return value Object returnvalue = null;
		Beforemethod ();
		Invoke methods can be invoked with the method and the Methodproxy parameters, and the effects performed are as//returnvalue = Methodproxy.invoke (target, args);
		returnvalue = Method.invoke (target, args);
		Aftermethod ();
	Return returnvalue;
	public void Beforemethod () {System.out.println ("operation before----method----");
	public void Aftermethod () {System.out.println (action after----method----);

The test class Proxytest package www.csdn.spring.proxy.cglib;

Import Org.junit.Test;
		public class Proxytest {@Test public void Testsay () {//true theme role SayHello SayHello = new SayHello (); Sayhello.say ("Hi. How are you doing?
		
		"); An object of the target class was created, and the JDK dynamic proxy creates an interface class object that cglib the object SayHello sh = (sayhello) new Cglibproxy () by creating a target class directly because it does not implement any interfaces.
		Createproxyinstance (SayHello); Sh.say ("Hi. How are you doing?
	");

 }

}


 

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.