Dynamic agent of Java

Source: Internet
Author: User

First, the basic concept of the agent
1, the Life of the agent: for example, buy a computer we often buy from agents, rather than directly to the headquarters directly to buy, no matter where to buy the computer is the same, from the agent there to buy we can not run to run, save a lot of trouble.
2, the agent in the program: to the existence of multiple target classes with the same interface (known as the Delegate Class) to add the function of the system, such as exception handling, journaling, method run time, transaction management and so on, then how to do it? If we directly modify the interface implementation is clearly contrary to the open and close principle, the program error-prone. One approach is to write a proxy class that has the same interface as the target class, and the proxy class invokes the method of the target class and adds the system's functionality.
3, the client calls the problem: we call in the client, sometimes need to switch the target class or proxy class, such as journaling, running time, etc., in our system after the stability of the use of target class, then how to achieve a convenient switch it? Through the management of the Factory mode and configuration file, it is convenient to switch the target class to the proxy class even if the source program of the client is not modified.
4, Static proxy: Static proxy is a manual form for the target class to add the proxy class and the target interface method, the target class increases when the proxy class also needs to be increased, so that with the increase in class resulting in class explosion problems. 2nd, when the target interface increases, both the target class and the proxy class are going to be implemented again, which also increases the complexity of the programming.
5, dynamic Agent: Dynamic agent is the target interface of all methods and subclasses of the centralized processing, through the JVM mechanism of dynamic generation, with a proxy class on the line. The dynamic agent needs to implement the Invocationhandler interface.
6, dynamic Agent Benefits: (1) The target interface each add a method does not have to do the implementation. (2) The target subclass does not need to add a proxy class each time it adds one.
7. CGLIB: If you want to provide dynamic proxy functionality for a class that does not implement an interface, you can use the CGLIB library.
8, AOP: The aspect-oriented programming, AOP solves the problem of cross-service (crossover business is the business interspersed to a certain aspect of the system function), in order to solve this kind of business can use proxy technology, so agent technology is the key and core technology of AOP.
Second, the use of agents
1. Static Agent
Abstract class Code:
/** * Theme interface, or Target class interface * @author Zhu * */public interface Subject {void dosomething ();//void Dootherthing ();}


Target Class Code:
public class Target implements Subject {@Overridepublic void dosomething () {System.out.println ("target class Method");}}


Proxy class Code:
public class Proxy implements Subject {private target target = new target (); @Overridepublic void DoSomething () {System.out . println ("system function: Before execution! "); target.dosomething (); SYSTEM.OUT.PRINTLN ("system function: After execution! ");}}


Client code:
public class Client {public static void main (string[] args) {Subject Subject = new Proxy (); subject.dosomething ();}}


As you can see from the code above, the proxy classes are implemented every time a method is added to the target class interface. Also, without adding a target class, the proxy class would have to add one. So how do we solve these problems? is the dynamic agent.
2. Dynamic Agent: Get collection Collection by Dynamic proxy method
(1) Three-step implementation
Class clazzProxy1 = Proxy.getproxyclass (Collection.class.getClassLoader (), collection.class);//First step: Get the Class bytecode object                 Constructor Constructor = Clazzproxy1.getconstructor (Invocationhandler.class);//Second step: Get the constructor class from class                 MyInvocationHander1 implements invocationhandler{public        object Invoke (Object proxy, Method method, object[] args) C3/>throws throwable {          return null;}        } Collection proxy = (Collection) constructor.newinstance (New MyInvocationHander1 ());//Step three: Get the Collection proxy class


(2) One-step implementation
Final ArrayList target = new ArrayList (); Collection proxy = (Collection) proxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (), new Invocationhandler () {public object Invoke (Object Proxy, Method method, object[] args) throws Throwable {return null;}});


3. Create a Collection object through the dynamic agent mechanism and encapsulate
Interface class:
public interface Advice {void Beforemethod (method method); void Aftermethod (method);}


Interface Implementation class:
public class Myadvice implements Advice {long beginTime = 0;public void Aftermethod (Method method) {//TODO auto-generated Method StubSystem.out.println ("graduated from the Preach Wisdom Podcast to work!") "); Long endTime = System.currenttimemillis (); System.out.println (Method.getname () + "Running Time of" + (Endtime-begintime));} public void Beforemethod (method) {//TODO auto-generated method StubSystem.out.println ("Go to Preach Intelligence podcast to learn!") "); beginTime = System.currenttimemillis ();}}


To get the Proxy method:
Private static Object GetProxy (Final object target,final Advice Advice) {Object proxy3 = proxy.newproxyinstance (target.ge Tclass (). getClassLoader (),/*new Class[]{collection.class},*/target.getclass (). Getinterfaces (), New Invocationhandler () {public object Invoke (object proxy, Method method, object[] args) throws Throwable {/*long beginTime = S Ystem.currenttimemillis (); Object retVal = Method.invoke (target, args); Long endTime = System.currenttimemillis (); System.out.println (Method.getname () + "Running Time of" + (Endtime-begintime)); return Retval;*/advice.beforemethod (Me Thod); Object retVal = Method.invoke (target, args); Advice.aftermethod (method); return retVal;}}); return proxy3;}


Client calls:
  Final ArrayList target = new ArrayList ();  Collection proxy = (Collection) getproxy (target,new myadvice ());  Proxy.add ("Zxx");

Summary: What information does the JVM need to create a dynamic proxy class?
1) What methods are in the generated class that are notified by the way they implement which interfaces.
2) The bytecode of the generated class must have an associated class loader object.
3) The method of producing the class is provided by the client code.
Iv. internal principles of dynamic agents
1, the dynamically generated class implements the Target interface collection (can implement several interfaces), the production class has the collection interface all methods and a receiving Invocationhandler entry construction method.
2, the construction method receives the Invocationhandler parameter, is used to facilitate us to realize the system function, here through the reflection mechanism dynamic processing.
3. Three parameters in the Invocationhandler interface
Invoke (Object proxy, method, object[] args): Proxy is an instance object of an agent such as an collection interface, method refers to an interface, and args refers to a parameter in a method.
4. Why does the GetClass () method of the instance object of the dynamic class return the correct result?
When a proxy object is invoked, Hashcode, toString, equals several methods are inherited from object, proxy object requests are forwarded to the Invocationhandler object, and other methods for object do not forward the proxy.
Third, agent and application
1. Realize the encapsulation and configuration of AOP function: In our AOP framework, the user can switch to the proxy class through the configuration file, which makes it convenient and flexible to switch the system functions, such as log. In such a framework has a bean factory, through the factory we can get the instance object of the class, in the project we encapsulated the agent factory, thus realizing the agent function.
(1) Bean Factory: Factory class Beanfactory is responsible for creating an instance object of the target class or proxy class and switching through the configuration file. Its Getbean method returns an appropriate instance object based on the parameter string, if the parameter string in the configuration file corresponds to the class name is not Proxyfactorybean, then returns the instance object of the class directly, otherwise, returns the object returned by the GetProxy method of the class instance object. Beanfactory construction method receives the input stream object representing the configuration file, the configuration file format
As follows:
#xxx =java.util.arraylist
Xxx=cn.itcast.proxyfactorybean
Xxx.target=java.util.arraylist

Xxx.advice=cn.itcast.myadvice

public class Beanfactory {Properties props = new Properties ();p ublic beanfactory ( InputStream IPs) {try {props.load (IPs)} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} public Object Getbean (string name) {String className = Props.getproperty (name); object Bean = Null;try {Class clazz = class. Forname (className); bean = Clazz.newinstance ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} if (Bean instanceof Proxyfactorybean) {Object Proxy = null; Proxyfactorybean Proxyfactorybean = (Proxyfactorybean) bean;try {Advice Advice = (Advice) class.forname ( Props.getproperty (name + ". Advice")). newinstance (); Object target = Class.forName (Props.getproperty (name + ". Target")) . newinstance ();p roxyfactorybean.setadvice (advice);p Roxyfactorybean.settarget (target);p roxy = Proxyfactorybean.getproxy ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} return proxy;} return bean;}} 

(2) Proxyfacotrybean acts as a factory for encapsulating dynamic agents, what configuration parameter information is required for the factory class? Goals and Notices
public class Proxyfactorybean {private Advice advice;private Object target;public Advice Getadvice () {return advice;} public void Setadvice (Advice Advice) {this.advice = Advice;} Public Object Gettarget () {return target;} public void Settarget (Object target) {this.target = target;} Public Object GetProxy () {//TODO auto-generated method Stubobject Proxy3 = Proxy.newproxyinstance (Target.getclass (). getClassLoader (),/*new Class[]{collection.class},*/target.getclass (). Getinterfaces (), new InvocationHandler () { public object invoke (object proxy, Method method, object[] args) throws Throwable {/*long beginTime = System.currenttimemil Lis (); Object retVal = Method.invoke (target, args); Long endTime = System.currenttimemillis (); System.out.println (Method.getname () + "Running Time of" + (Endtime-begintime)); return Retval;*/advice.beforemethod (Me Thod); Object retVal = Method.invoke (target, args); Advice.aftermethod (method); return retVal;}}); return proxy3;}} 


(3) Client program
public class Aopframeworktest {//Get target object and advertise object through configuration file/*** 1, get configuration file * 2, Get class instance object by class name */public static void Main (string[] args ) throws Exception {//TODO auto-generated method Stubinputstream ips = AopFrameworkTest.class.getResourceAsStream (" Config.properties "); Object bean = new Beanfactory (IPS). Getbean (" xxx "); System.out.println (Bean.getclass (). GetName ());//((Collection) bean). Clear ();}}

2. Agent and JDBC

A typical application of dynamic agent is to implement the connection pool of database. Because the programmer using JDBC is accustomed to closing the connection by invoking the Close method of the object after using the database's connection object, the connection pool loses its role. We can use dynamic Agent technology to solve this problem, when the programmer calls connection's Close method, we intercept it and return it to the connection pool instead of shutting down the physical connection directly.


Dynamic agent of Java

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.