This is the sixth day of my participation in Gwen Challenge

The so-called dynamic proxy, simply speaking, is actually during the running of the program, dynamically generate a proxy object to achieve the enhancement of the target object method. Proxy object = target object + enhancement code

Before we talk about dynamic proxies, let’s look at static proxies.

Static proxy

For example, assuming that every single friend has courtship skills, we can define a single interface, and then this interface has a courtship method as follows:

public interface SingleDog {

   String courtShip(a);// Marriage skills
}
Copy the code

Then our protagonist, Xiao Wang, graduated five years ago. Although he is still single, he is lucky enough to have this skill.

public class DogWang implements SingleDog {
    @Override
    public String courtShip(a) {
        return "Bao, I crossed the street today. What road did I cross? There's no turning back."; }}Copy the code

We all know that Xiao Wang has a way of falling in love, but as a social worker, he has to go to work and go to work. He has been struggling to meet a suitable girl to use his skills. At the same time this age single unmarried, but the queen mother in the home nasty bad, hurriedly introduced the daughter of a friend xiaoning to his son. All right, the queen mother here is our proxy

public class WorryMom implements SingleDog {

    private DogWang dogWang;

    public WorryMom(DogWang dogWang) {
        this.dogWang = dogWang;
    }

    @Override
    public String courtShip(a) {
        // Introduce Xiaoning to my son
        System.out.println("this is miss ning's wechat");
        String honeyWord = dogWang.courtShip();
        // Be patient and tell my son to keep in touch
        System.out.println("if you fail,get the fu** out of my home");
        returnhoneyWord; }}Copy the code

Wang ma, as a surrogate, will not actually fall in love. But through the construction method into xiao Wang, can be understood as taking Xiao Wang to see Xiao Ning. Finally, the real love or our protagonist Xiao Wang. But her mother’s advice helped Xiao Wang to complete the task better to some extent

Disadvantages of static proxies

In fact, Wang Ma may have more than one son, so every time she adds a son, she needs to increase the hard coding, which has a strong coupling, and it is certainly very troublesome to maintain.

Dynamic proxy

Static proxies are clearly understood by the examples above, but what about dynamic proxies? Provides the Java JDK. Lang. Reflect the InvocationHandler interface and Java. Lang. Reflect. The Proxy class, these two classes to cooperate with each other to realize our dynamic Proxy.

Proxy has a static method getProxyClass to get the Proxy object for the interface

public static void main(String[] args) throws Exception {
        // Get the proxy class object of the interface. Parameter 1 is the corresponding class loader, and parameter 2 is the corresponding interfaceClass<? > proxyClass = Proxy.getProxyClass(SingleDog.class.getClassLoader(), SingleDog.class);// Get the corresponding parameterized constructorConstructor<? > constructor =proxyClass.getConstructor(InvocationHandler.class); SingleDog dogWang = (SingleDog) constructor.newInstance(new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // Invoke has no target object, manually new one
                DogWang dogWang = new DogWang();
                System.out.println("this is miss ning's wechat");
                Object invoke = method.invoke(dogWang, args);
                System.out.println("if you fail,get the fu** out of my home");
                returninvoke; }}); dogWang.courtShip(); }Copy the code

The invoke method of the above code has no target object, so you have to manually create a new king, which is definitely not a hard-coded approach. We can write a method specifically to get the proxy class object, taking the target object as an argument. As follows:

public static Object getProxy(final Object target) throws Exception {
        // Get the proxy class object for the interfaceClass<? > proxyClass = Proxy.getProxyClass(target.getClass().getClassLoader(), target.getClass().getInterfaces());// Get the corresponding parameterized constructorConstructor<? > constructor = proxyClass.getConstructor(InvocationHandler.class); Object proxy = constructor.newInstance(new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("this is miss ning's wechat");
                Object invoke = method.invoke(target, args);
                System.out.println("if you fail,get the fu** out of my home");
                returninvoke; }});return proxy;
    }
Copy the code

Call to pass in the target object:

public static void main(String[] args) throws Exception {
        SingleDog singleDog = (SingleDog) getProxy(new DogWang());
        singleDog.courtShip();
    }
Copy the code

This is a perfect implementation of the JDK dynamic Proxy, but in daily use, it is usually implemented using another Proxy method, Proxy#newProxyInstance. This approach more succinctly implements dynamic proxies. As follows:

public static Object getProxy(final Object target) throws Exception {
        Object instance = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("this is miss ning's wechat");
                Object invoke = method.invoke(target, args);
                System.out.println("if you fail,get the fu** out of my home");
                returninvoke; }});return instance;
    }
Copy the code

Today is the whole four months of disconnection with the person I like, I can’t see the future, sometimes I feel very painful, I still have to bury my head in the road.

Let’s hope everyone gets a glimpse of the light of day before the chillers roll the blades.

Above, thank you for seeing this.