Java Dynamic Agent mechanism-the skills that make your interview stand out

Source: Internet
Author: User
Tags throwable

Retrofit is a very high decoupling network request framework, recently discovered in the study of dynamic agent this very powerful and practical technology, this article will be as a retrofit of knowledge, let us know: Dynamic agent has what application scenarios, what is dynamic agent, how to use, Where is its limitation?
#动态代理的应用场景

1. aop--oriented programming, program decoupling
In short, when you want to do some of the internal methods of some classes, do some common things before and after execution, and perform personalization actions in the method-with dynamic proxies. Can reduce the amount of code and enhance maintainability when the volume of business is large.

2. Want to customize some of the methods in the third-class library
I quoted a third-party class library, but some of his methods did not meet my needs, I would like to rewrite those methods, or add some special operations before and after the method-with dynamic proxy. However, it is important to note that these methods have limitations and I will explain them later.

What is dynamic proxy

The above graph is too abstract, we start from the example of life.

If you are a big landlord (the agent), you have a lot of houses want to rent, and you find the tenants too troublesome, not willing to do their own, so you find a person to represent you (agent), to help care for these things, And this person (agent is the intermediary) to help you rent a house when you charge some of the corresponding intermediary fees (for housing rental of some additional operations). For tenants, the intermediary is the landlord, agent you do some things.

Above, is an example of a proxy, and why he called the dynamic agent, "dynamic" two words in what place?

We can think of this, if you have every house you have an agent to help you, every time you want to rent a house, you have to hire another, so you will ask a lot of agents, expensive intermediary costs, which can be regarded as often said "static agent."

But if we give all the house to an intermediary agent, let him in the multi-house dynamic switch identity, to help you deal with every tenant. This is the process of a "dynamic agent". A major feature of dynamic proxies is that there is no proxy class at runtime to generate proxy classes at compile time.

Let's take a look at some code.

How to rent a house
/***定义一个借口**/public interface RentHouse {void rent();//房屋出租void charge(String str);//出租费用收取}
Landlord
public class HouseOwner implements RentHouse {public void rent() {    System.out.println("I want to rent my house");}public void charge(String str) {    System.out.println("You get : " + str + " RMB HouseCharge.");}}
Mediation
public class DynamicProxy implements InvocationHandler {// 这个就是我们要代理的真实对象,即房东private Object subject;//  构造方法,给我们要代理的真实对象赋初值public DynamicProxy(Object subject) {    this.subject = subject;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {    //  在代理真实对象前我们可以添加一些自己的操作,中介收取中介费    System.out.println("before "+method.getName()+" house");    System.out.println("Method:" + method.getName());    //        如果方法是 charge 则中介收取100元中介费    if (method.getName().equals("charge")) {        method.invoke(subject, args);        System.out.println("I will get 100 RMB ProxyCharge.");    } else {        //    当代理对象调用真实对象的方法时,其会自动的跳转到代理对象关联的handler对象的invoke方法来进行调用        method.invoke(subject, args);    }    //  在代理真实对象后我们也可以添加一些自己的操作    System.out.println("after "+method.getName()+" house");    return null;}
Guests
public class Client {public static void main(String[] args){    //    我们要代理的真实对象--房东    HouseOwner houseOwner = new HouseOwner();    //    我们要代理哪个真实对象,就将该对象传进去,最后是通过该真实对象来调用其方法的    InvocationHandler handler = new DynamicProxy(houseOwner);    /*     * 通过Proxy的newProxyInstance方法来创建我们的代理对象,我们来看看其三个参数     * 第一个参数 handler.getClass().getClassLoader() ,我们这里使用handler这个类的ClassLoader对象来加载我们的代理对象     * 第二个参数realSubject.getClass().getInterfaces(),我们这里为代理对象提供的接口是真实对象所实行的接口,表示我要代理的是该真实对象,这样我就能调用这组接口中的方法了     * 第三个参数handler, 我们这里将这个代理对象关联到了上方的 InvocationHandler 这个对象上     */    RentHouse rentHouse = (RentHouse) Proxy.newProxyInstance(handler.getClass().getClassLoader(), houseOwner            .getClass().getInterfaces(), handler);//一个动态代理类,中介    System.out.println(rentHouse.getClass().getName());    rentHouse.rent();    rentHouse.charge("10000");}}

Let's take a look at the output

com.sun.proxy.$Proxy0before rent houseMethod:rentI want to rent my houseafter rent housebefore charge houseMethod:chargeYou get : 10000 RMB HouseCharge.I will get 100 RMB ProxyCharge.after charge houseProcess finished with exit code 0

The output has before rent house and after rent, which shows that we can add operations before and after the method. Then look at the output I will get the RMB proxycharge. The intermediary charged a 100 block fee, stating that we can not only increase the operation, can even replace the method or directly let the method do not execute.

You may have a lot of doubts just starting with the code, and we'll look at what the dynamic agent should do with the following content.

#动态代理该如何使用
In the dynamic agent mechanism of Java, there are two important classes and interfaces, one is Invocationhandler (Interface), the other is proxy (class), and this class and interface is necessary to implement our dynamic proxy.

Each dynamic proxy class must implement the Invocationhandler interface (the mediation in the code), and each instance of the proxy class is associated with a handler, and when we call a method through the proxy object, The invocation of this method is forwarded as a method called by the invoke of the Invocationhandler interface (which is written in the face of the enhancement of the method).

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

We see that this method takes three parameters altogether, so what do these three parameters represent?

Object invoke(Object proxy, Method method, Object[] args) throws Throwable//proxy:  指代我们所代理的那个真实对象//method:  指代的是我们所要调用真实对象的某个方法的Method对象//args:  指代的是调用真实对象某个方法时接受的参数

Next, let's look at the proxy class.

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,  InvocationHandler h)  throws IllegalArgumentException

The role of the proxy class is to dynamically create a class of proxy objects, which provides a number of methods, but the most we use is newproxyinstance this method:

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,  InvocationHandler h)  throws IllegalArgumentException

The function of this method is to get a dynamic proxy object, which receives three parameters, and we take a look at the meanings represented by these three parameters

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException//loader:  一个ClassLoader对象,定义了由哪个ClassLoader对象来对生成的代理对象进行加载//interfaces:  一个Interface对象的数组,表示的是我将要给我需要代理的对象提供一组什么接口,如果我提供了一组接口给它,那么这个代理对象就宣称实现了该接口(多态),这样我就能调用这组接口中的方法了//h:  一个InvocationHandler对象,表示的是当我这个动态代理对象在调用方法的时候,会关联到哪一个InvocationHandler对象上

So, with the code given above, we can understand how dynamic proxies are used.

#动态代理的局限性
From the use of dynamic agents we see in fact can be enhanced by the method is to implement the pretext (the public method does not implement the pretext can also be inherited by the proxy class to use), the code of Houseowner inherited Renthouse. And for the private method JDK Dynamic agent powerless!
The above dynamic agent is the JDK, and for the Java project also has the famous cglib, but unfortunately Cglib does not use in Android, the Android virtual machine relative and the JVM still has the difference.

Conclusion

The use of dynamic agents is far more than this, the internal principle will be described in a future article, but the application of class reflection temporarily generated proxy class This mechanism determines that it will have a certain impact on performance. This article as retrofit principle of the predecessor article is not too exhaustive, if there are omissions and errors, please correct me!

Java Dynamic Agent mechanism-the skills that make your interview stand out

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.