Java Dynamic Agents (JDK and Cglib)

Source: Internet
Author: User

Java Reflection mechanism
The Java reflection mechanism in the running state, for any class, can know all the properties and methods of this class, for any one object, can call any of its methods and properties; This dynamically acquired information and the ability to dynamically invoke the method of the object is called the reflection mechanism of the Java language. Java Reflection (emission) mechanism: "When a program is run, it is allowed to change the program structure or variable type, which is called Dynamic language." From this point of view, Perl,python,ruby is a dynamic language, and c++,java,c# is not a dynamic language. But Java has a very prominent dynamic-related mechanism: Reflection, in Java, refers to the classes that we can load, detect, and use completely unknown during compilation at runtime. In other words, a Java program can load a runtime to know the name of a class, learn its full construct (but not including the methods definition), and generate its object entities, or set values on its fields, or evoke its methods.
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.
The dynamic agent mechanism of JDK can only implement the class of the interface, and the class that cannot implement the interface cannot implement the dynamic proxy of the JDK, the cglib is to implement the proxy for the class, his principle is to generate a subclass for the target class, and overwrite the method implementation enhancement, but because inherit is adopted, Therefore, the final decorated class cannot be proxied.
Pom.xml introducing the relevant jar
<dependency><groupid>cglib</groupid><artifactid>cglib</artifactid><version >3.1</version></dependency>

Code
Package Com.eyugame.test.proxy;import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;import java.lang.reflect.proxy;/** * JDK comes with dynamic proxy * @author JYC506 * */public class Jdkproxy implements Invocationhandler {private O Bject target;/** * Binds the delegate object and returns a proxy class * * @param T * class to Proxy * @return * @throws illegalaccessexception * @throws in Stantiationexception */@SuppressWarnings ("unchecked") public <superClazz> Superclazz getinstance (class<? > T,class<?> superclazz) throws Instantiationexception, illegalaccessexception {this.target = T.newInstance () ;//Get proxy object return (Superclazz) proxy.newproxyinstance (T.getclassloader (), t.getinterfaces (), this); To bind the interface (this is a flaw, cglib compensates for this flaw)}/** * Binds the delegate object and returns a proxy class * * @param T * class to Proxy * @return * @throws ILLEGALACCESSEXCEP tion * @throws instantiationexception * * @SuppressWarnings ("unchecked") public <superClazz> Superclazz getinstance (Object target,class<?> superclazz) {this.target =target; class<?> Clazz=this.target.getclass ()//Get proxy object return (Superclazz) proxy.newproxyinstance (Clazz.getclassloader (), Clazz.getinterfaces (), this); To bind the interface (this is a flaw, cglib compensates for this flaw)}/** * */public object Invoke (Object proxy, method, object[] args) throws Throw able {Object result = null; System.out.println ("things start"); result = Method.invoke (target, args); System.out.println ("End of Thing"); return result;} public static void Main (string[] args) {Jdkproxy proxy = new Jdkproxy (); Idog dog1 = Null;idog dog2=new Dog (); try {dog1 = P Roxy.getinstance (Dog.class,idog.class);d og2=proxy.getinstance (New Dog (), Idog.class);d og1.dosomething (); Dog2.setid (23); System.out.println (Dog2.getid ());} catch (Exception e) {e.printstacktrace ();}}}    Class Dog implements Idog {private int id; public void DoSomething () {System.out.println ("Call DoSomething ()"); @Overridepublic void setId (int id) {this.id=id;} @Overridepublic int getId () {return this.id;}} Interface Idog {void dosomething (); void setId (int id); int getId ();}
Run results

Package Com.eyugame.test.proxy;import Java.lang.reflect.method;import Net.sf.cglib.proxy.enhancer;import Net.sf.cglib.proxy.methodinterceptor;import net.sf.cglib.proxy.methodproxy;/** * cglib Dynamic Agent * @author JYC506 * */public Class Cglibproxy implements Methodinterceptor {/** * Create proxy Object * * @param target * @return */@SuppressWarnings ("unchecked") p Ublic <T> T getinstance (class<?> t) {enhancer enhancer = new enhancer ();/* Specify parent class */enhancer.setsuperclass (t); /callback Method Enhancer.setcallback (this);//Create proxy object return (T) enhancer.create ();} @Override//callback method public Object intercept (object obj, Method method, object[] args, Methodproxy proxy) throws Throwable {Sys Tem.out.println ("things start"); Object o = Proxy.invokesuper (obj, args); System.out.println ("End of Thing"); return o;} public static void Main (string[] args) {Cglibproxy proxy = new Cglibproxy (); People people = proxy.getinstance (people.class);p Eople.setid (23); System.out.println (People.getid ());}} class People {private int id;private String username;privateint age;public int getId () {System.out.println ("Get ID"); return ID;} public void setId (int id) {SYSTEM.OUT.PRINTLN ("Assign value to ID"); this.id = ID;} Public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} public int getage () {return age;} public void Setage (int.) {this.age = age;}}


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.