Proxy dynamic Agent Invocationhandler CGLIB

Source: Internet
Author: User

Proxy dynamic Agent Invocationhandler CGLIB


Invocationhandler interface
proxy class
Brief introduction
Properties that the proxy class has
Properties that the proxy instance has
Methods for repeating in multi-agent interfaces
Underlying implementation principle
CGLIB Introduction

Invocationhandler interface

InvocationHandleris the interface implemented by the invocation handler a proxy instance .

Each have an proxy instance associated invocation handler . When a method was invoked on a proxy instance , the method invocation was encoded and to the dispatched invoke method of its invocation handler .

When a method is called on a proxy instance, the method call is encoded and assigned to the Invoke method of its calling handler.

Define the method:

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;

Processes A on method invocation A and proxy instance returns the result. This method would be invoked on the When invocation handler a method is invoked on a, that it's associated with proxy instance .

Processes the method call on the proxy instance and returns the result. This method is called on the calling handler when the method is called on the proxy instance associated with the method.


    • proxy-The that the proxy instance method is invoked on

      The proxy instance on which to invoke the method

    • method-the Method instance corresponding to the interface method invoked on the proxy instance .

      The method instance that corresponds to the interface methods that are called on the proxy instance.

    • args-An array of objects containing method invocation proxy instance the values of the arguments passed in the the, or null if interface method takes n o arguments.

      代理实例 方法调用 An array of objects containing the parameter values passed in, or null if the interface method does not use parameters.

return value:
The value to return from the on the method invocation proxy instance .

The value returned from the method call of the proxy instance.

proxy class
public class java.lang.reflect.Proxy extends Object implements
Brief introduction

Proxy provides static methods for creating dynamic proxy classes and instances , and it's also the superclass of all dynamic proxy classes created by those methods.

To create a proxy for some interface Foo:

InvocationHandler handler = new MyInvocationHandler(new FooImpl());//FooImpl是实现Foo接口的委托类Foo f = (Foo) Proxy.getProxyClass(Foo.class.getClassLoader(), new Class[] { Foo.class })    .getConstructor(new Class[] { InvocationHandler.class })    .newInstance(new Object[] { handler });

or more simply:

Foo proxy = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),//定义了由哪个ClassLoader对象来对生成的代理对象进行加载        new Class[] { Foo.class },//表示的是我将要给我需要代理的对象提供一组什么接口,之后我这个代理对象就会实现了这组接口        handler);//表示的是当我这个动态代理对象在调用方法的时候,会关联到哪一个InvocationHandler对象上

A dynamic proxy class is-a class that implements a list of interfaces when specified at runtime the class is created, with behavior as described below.

    • A is the such an interface, which is proxy interface implemented by a proxy class.
    • A is a proxy instance instance of a proxy class.
    • Each proxy instance have an associated invocation handler object, which implements the interface InvocationHandler .
    • A method invocation on a through one of its'll be proxy instance proxy interfaces dispatched to the Invoke method of the instance ' s invocation handler , p Assing proxy instance The, a java.lang.reflect.Method object identifying the method that is invoked, and an array of type Object containing the Argum Ents.
    • The invocation handler processes the encoded method invocation as appropriate and the result that it returns would be returned as the R Esult of the on the method invocation proxy instance .
Properties that the proxy class has
  • The proxy class is public, final, and not abstract.

    System.out.println (Modifier.tostring (Proxy.getclass () getmodifiers ()));//final
    System.out.println (Modifier.tostring (Proxy.class.getModifiers ()));//public

  • The unqualified name of the proxy class was not specified. However, the class name space beginning with the string "$Proxy" should be reserved for the proxy class.

    System.out.println (Proxy.getclass (). GetName ());//"$Proxy 0"

  • Proxy classes are extends Java.lang.reflect.Proxy.
  • The proxy class accurately implements the interface specified when it was created, in the same order.
  • If the proxy class implements a non-public interface, it is defined in the same package as the interface. Otherwise, the package for the proxy class is not specified. Note that package sealing will not block the successful definition of the proxy class at run time in a particular package, nor will it block classes defined by the same classloader and packages with a specific signature.
  • Because the proxy class will implement all interfaces specified at the time of its creation, calling Getinterfaces on its class object will return an array containing the same list of interfaces, and calling GetMethods on its class object will return a method that includes all the methods in those interfaces. Object, and calling GetMethod will find some of the expected methods in the proxy interface.
  • If the Proxy.isproxyclass method passes the proxy class (the class returned by Proxy.getproxyclass, or the class of the object returned by Proxy.newproxyinstance), the method returns True, otherwise false.
  • The of the proxy class is the same as the system class loaded by the bootstrap ClassLoader (such as Java.lang.Object), because the code for the proxy class is generated by the trusted system code. This protection domain is typically granted
  • Each proxy class has a public construction method that can take one parameter (an implementation of interface Invocationhandler) to set the invocation handler for the proxy instance. You do not have to use the reflection API to access public construction methods, and you can create proxy instances by calling the Proxy.newinstance method, which combines the operation that invokes Proxy.getproxyclass with the constructor method that invokes the handler.
Properties that the proxy instance has
  • Given a proxy instance proxy and one of the interfaces implemented by its proxy class Foo, the expression proxy instanceof Foo will return true, and (Foo) proxy the mandatory The conversion operation will succeed without throwing classcastexception.
  • Each have an proxy instance associated invocation handler , the one is passed to its constructor. The static method would return the associated with the passed as its Proxy.getInvocationHandler invocation handler proxy instance argument.

    System.out.println (Proxy.getinvocationhandler (Proxy) = = handler);//true

  • An on a would be encoded and dispatched to the as described in the documentation for that interface method invocation proxy instance invocation handler‘s invoke method method.
  • An invocation of the hashCode, equals, or toString methods declared in Java.lang.Object on a would be proxy instance encoded and dispatched to the invocation handler‘s invoke method The same manner interface method invocations as is encoded and dispatched, as described above.

    Overriding the Equals, Hashcode, toString of the object class, all of them simply call the Invocationhandler invoke method, which means that it can be operated in a special way, that is, the JDK's dynamic agent can also proxy the above three methods.

  • The declaring class of the Method object passed to invoke'll be java.lang.Object .
  • Other public methods of a proxy instance inherited from java.lang.Object is not overridden by a proxy class, so-like they does for invocations of those methods behave Instan Ces of java.lang.Object .
Methods for repeating in multi-agent interfaces

Messy, this problem is best avoided when designing.



protected InvocationHandler hThe invocation handler for this proxy instance.

Construction method

protected Proxy(InvocationHandler h)Constructs a new proxy instance from a subclass (typically a dynamic proxy class) and assigns a value to its invocation handler.

Public methods

    • static InvocationHandler getInvocationHandler(Object proxy)Returns the invocation handler for the specified proxy instance.
    • static boolean isProxyClass(Class<?> cl)Returns True when and only if the specified class is getProxyClass newProxyInstance dynamically generated as a proxy class through a method or method.
    • Static class<> Getproxyclass (ClassLoader loader, class<> ... interfaces) returns the Java.lang.Class object of the proxy class, and provides a class loader and an array of interfaces to it.
    • static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)Returns a proxy class instance for the specified interface that can assign a method call to the specified invocation handler.

      Return value: A proxy instance of the specified invocation handler with the proxy class, defined by the specified class loader, and implements the specified interface

      • Loader-Class loader that defines the proxy class. Defines which ClassLoader object is to load the generated proxy object
      • Interfaces-the list of interfaces to be implemented by the proxy class. Is that I'm going to provide a set of interfaces for the object I need to proxy, and then I'll implement this set of interfaces for this proxy object.
      • H-The call handler that assigns the method call. Indicates which Invocationhandler object the dynamic proxy object will be associated with when calling the method.
Underlying implementation principle

The dynamic proxy for the JDK is best known for possible implementations of the spring AOP, which by default is implemented by the 接口 dynamic proxy of the JDK used by, and for the proxy using Cglib.

The JDK supports dynamic proxies starting from 1.3. The dynamic agent of the JDK is to dynamically generate the class files of the proxy classes and load the running process in the process of running the program, according to the interface of the agent.

Proxy class inherits the proxy class, implements the interface of the agent, because Java can not inherit more, so the proxy class can no longer inherit other classes, so the dynamic agent of the JDK does not support the agent of the class, only support the agent of the interface.

Within the interface method implemented by the proxy class, it simply invokes the Invocationhandler invoke method without invoking the method of the interface implemented by the delegate class, so for the user, the effect is that the interface method of the delegate class is represented by the proxy class (or interception).

If we do some special operations in the Invocationhandler invoke method, or even return directly, this is basically a simple implementation of AOP. Of course, it is common practice that in the Invoke method 通过反射调用目标对象的接口方法 , you can insert any required logic before and after the method execution of the target object to enhance the functionality, as needed.

CGLIB Introduction

GitHub Home

You need to add two jar packages:
CGLib 2.2
ASM 3.3.1

Byte Code Generation Libraryis high level API to generate and transform JAVA byte code . It AOP is used by, testing to data access frameworks generate and dynamic proxy objects intercept field access .

The JDK provides a dynamic proxy from version 1.3, which is very simple to use, but with one obvious drawback: 需要目标对象实现一个或多个接口 . Using Cglib you can implement dynamic proxy functionality even if the proxy class does not implement any interfaces.

Cglib is a powerful, high-performance code-generation library that is easy to use and it's 运行速度要远远快于JDK的动态代理 . Within the implementation, the Cglib library uses ASM this one 轻量但高性能 bytecode manipulation framework to convert bytecode and generate new classes. ASM uses a SAX parser-like mechanism to achieve high performance. PS: Using ASM requires a good understanding of the JVM, including class file formats and instruction sets.

Cglib is widely used in proxy-based AOP frameworks to provide method interception (such as Spring AOP and DYNAOP). Hibernate, as the most popular ORM tool, also uses the Cglib library to proxy single-ended associations. Easymock and Jmock as popular Java test libraries, they provide mock objects in a way that supports testing, using Cglib to proxy classes that do not have interfaces.

The principle of cglib is through 字节码 technology as a class 创建子类 and technology adopted in subclasses 方法拦截 拦截所有父类方法的调用 . Because of this, it is 通过创建子类来代理父类 not possible to proxy the final decorated class (the proxy- final decorated class throws an exception, and the proxy final -decorated method executes only the method of the delegate class as is, and cannot do any interception).

But Cglib has a fatal disadvantage: the bottom of cglib is the use of the well-known ASM bytecode generation framework, using bytecode technology to generate proxy classes, that is, by manipulating bytecode to generate a new. class file, while we are android loading in 优化后的.dex文件 , This means that we need to be able to dynamically generate the. dex file proxy class, so Cglib Android is not available in.


Proxy dynamic Agent Invocationhandler 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: 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.