search
HomeJavajavaTutorialA brief introduction to InvocationHandler of Java dynamic proxy
A brief introduction to InvocationHandler of Java dynamic proxyOct 22, 2018 pm 03:47 PM
javajavascriptjdk8acting

This article brings you a brief introduction to InvocationHandler of Java dynamic proxy. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

There are very in-depth articles on the Internet about Java's dynamic proxy, Proxy and InvocationHandler concepts. In fact, these concepts are not that complicated. Now we understand what InvocationHandler is through the simplest example. It is worth mentioning that InvocationHandler is widely used in Spring framework implementation, which means that if we understand InvocationHandler thoroughly, we will lay a solid foundation for future Spring source code learning.

Develop an interface that contains two methods that can greet "hello" or "goodbye" to the specified person.

public interface IHello {
   void sayHello(String name);
   void sayGoogBye(String name);
}

Create a simple class to implement this IHello interface.

public class Helloimplements implements IHello {
    @Override
    public void sayHello(String name) {
        System.out.println("Hello " + name);
    }
    @Override
    public void sayGoogBye(String name) {
        System.out.println(name+" GoodBye!");
    }
}

Consuming this implementation class is nothing special so far.

Now suppose we receive this requirement: The boss requires that every time the implementation class greets someone, the details of the greeting must be recorded in a log file. For the sake of simplicity, we print the following line of statement before greeting to simulate the logging action.

System.out.println("问候之前的日志记录...");

You may say, this is not simple? Directly modify the corresponding method of Helloimplements and insert this line of log into the corresponding method.

A brief introduction to InvocationHandler of Java dynamic proxy

However, the boss’s request is that you are not allowed to modify the original Helloimplements class. In real scenarios, Helloimplements may be provided by a third-party jar package, and we have no way to modify the code.

A brief introduction to InvocationHandler of Java dynamic proxy

You may say that we can use the proxy pattern in the design pattern, that is, create a new Java class as a proxy class, and also implement IHello interface and then pass an instance of the Helloimplements class into the proxy class. Although we are required not to modify the code of Helloimplements, we can write the logging code in the proxy class. The complete code is as follows:

public class StaticProxy implements IHello {

  private IHello iHello;

  public void setImpl(IHello impl){

  this.iHello = impl;

}

@Override

public void sayHello(String name) {

    System.out.println("问候之前的日志记录...");

    iHello.sayHello(name);

}

@Override

public void sayGoogBye(String name) {

     System.out.println("问候之前的日志记录...");

     iHello.sayGoogBye(name);

}

static public void main(String[] arg) {

     Helloimplements hello = new Helloimplements();

     StaticProxy proxy = new StaticProxy();

     proxy.setImpl(hello);

     proxy.sayHello("Jerry");

  }

}

This approach can achieve the requirements:

A brief introduction to InvocationHandler of Java dynamic proxy

Let’s look at how to use InvocationHandler to achieve the same effect. .

InvocationHandler是一个JDK提供的标准接口。看下面的代码:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DynaProxyHello implements InvocationHandler {
    private Object delegate;
    public Object bind(Object delegate) {
        this.delegate = delegate;
        return Proxy.newProxyInstance(
        this.delegate.getClass().getClassLoader(), this.delegate
        .getClass().getInterfaces(), this);
    }
    public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable {
        Object result = null;
        try {
            System.out.println("问候之前的日志记录...");
            // JVM通过这条语句执行原来的方法(反射机制)
            result = method.invoke(this.delegate, args);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

The bind method in the above code is very similar to the setImpl method of my previous proxy class StaticProxy, but the input parameter type of this bind method is more universal. The logging code is written in the method invoke.

See how to use it:

static public void main(String[] arg) {
    DynaProxyHello helloproxy = new DynaProxyHello();
    Helloimplements hello = new Helloimplements();
    IHello ihello = (IHello) helloproxy.bind(hello);
    ihello.sayHello("Jerry");
}

The execution effect is exactly the same as that of StaticProxy solution.

Let’s debug it first. When the bind method is executed, the method Proxy.newProxyInstance is called, and the instance of the Helloimplements class is passed in.

A brief introduction to InvocationHandler of Java dynamic proxy

We observe the ihello variable returned by the statement IHello ihello = (IHello) helloproxy.bind(hello) in the debugger. Although its static type is IHello, please note that when observing its actual type in the debugger, it is not an instance of Helloimplements, but one processed by the JVM, including the line of log we handwritten in the invoke method. Document the code. The ihello type is $Proxy0.

A brief introduction to InvocationHandler of Java dynamic proxy

When the sayHello method of this variable processed by the JVM is called, the JVM automatically transfers the call to DynaProxyHello.invoke:

A brief introduction to InvocationHandler of Java dynamic proxy

So, in the invoke method, our handwritten logging code is executed, and then the original sayHello code is executed through Java reflection.

Some friends may ask, your InvocationHandler seems more complicated than the static proxy StaticProxy? what is the benefit?

Assume that the boss's needs have changed again, and different logging strategies should be used in the methods of calling greetings and saying goodbye.

Let’s see how to use InvocationHandler to implement it elegantly:

A brief introduction to InvocationHandler of Java dynamic proxy

I hope this example can give everyone an understanding of Java’s dynamic proxy InvocationHandler. Get the most basic understanding.

The above is the detailed content of A brief introduction to InvocationHandler of Java dynamic proxy. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault思否. If there is any infringement, please contact admin@php.cn delete
Nginx反向代理中的代理防篡改策略Nginx反向代理中的代理防篡改策略Jun 11, 2023 am 09:09 AM

随着互联网的发展和应用程序的不断增多,Web服务器的作用越来越重要。在数据传输过程中,反向代理服务器已成为一个非常重要的角色,它可以帮助应用程序处理一些流量控制、负载均衡、缓存数据等问题,从而提高应用程序的性能和可靠性。Nginx是一个被广泛使用的轻量级Web服务器和反向代理服务器。在使用Nginx反向代理的过程中,对代理数据的完整性和防篡改性的保障显得尤为

如何使用Nginx代理服务器实现Web服务的动态SSL证书生成?如何使用Nginx代理服务器实现Web服务的动态SSL证书生成?Sep 05, 2023 pm 02:24 PM

如何使用Nginx代理服务器实现Web服务的动态SSL证书生成?Nginx是一款高性能的开源Web服务器,可以用于代理服务器、反向代理和负载均衡等多种用途。它的灵活性使得我们可以利用其强大的功能实现动态SSL证书生成,以提供更安全、更灵活的Web服务。本文将详细介绍如何利用Nginx代理服务器实现动态SSL证书生成。首先,我们需要生成一个自签名的根证书和私钥

十四年前的国游一哥,如今却被韩国公司收购?细数九城代理的牛叉游戏十四年前的国游一哥,如今却被韩国公司收购?细数九城代理的牛叉游戏Apr 02, 2024 am 09:58 AM

在十四年前,有这么一家公司,它坐拥着国内互联网游戏的半壁江山,腾讯看了它得点头,网易见了它得哈腰,乃至于像EA、暴雪这样的国际大公司都得看着它的眼色行事,人送外号国内游戏一哥。但经过这十多年的折腾,曾经的一哥却成了吊车尾的存在,别说是运营啥游戏了,就连公司都要被韩国小西八给收购了……今天,咱们就来回顾下,这个把《魔兽世界》、《激战》、《行星边际2》等一系列牛X游戏给引入国内的牛X公司——第九城市。出道即巅峰?靠着《奇迹MU》打下国内网游半壁江山讲道理,哪怕现在有腾讯、网易、米哈游、完美世界这么多

如何使用Java强制继承代理final类?如何使用Java强制继承代理final类?Sep 06, 2023 pm 01:27 PM

如何使用Java强制继承代理final类?在Java中,final关键字用于修饰类、方法和变量,表示它们不可被继承、重写和修改。然而,在某些情况下,我们可能需要强制继承一个final类,以实现特定的需求。本文将讨论如何使用代理模式来实现这样的功能。代理模式是一种结构型设计模式,它允许我们创建一个中间对象(代理对象),该对象可以控制对另一个对象(被代理对象)的

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

如何在Docker中配置Nginx来代理Web服务?如何在Docker中配置Nginx来代理Web服务?Sep 05, 2023 am 10:33 AM

如何在Docker中配置Nginx来代理Web服务?随着容器技术的快速发展,Docker已成为最常用的容器化平台之一。而Nginx作为一种高性能的Web服务器和反向代理服务器,也被广泛应用于各种Web服务的部署中。本文将介绍如何在Docker中配置Nginx来代理Web服务,并提供相应的代码示例。创建一个简单的Web应用首先,我们需要创建一个简单的Web应用

火狐浏览器代理连接服务器失败怎么办火狐浏览器代理连接服务器失败怎么办Jan 31, 2024 pm 03:30 PM

火狐浏览器代理连接服务器失败怎么办?火狐浏览器是一款很多小伙伴都在使用的一款浏览器软件,可以为我们提供非常便捷的上网搜索功能。不过有些小伙伴在使用火狐浏览器的时候,发现访问的部分网页无法无法连接服务器,兵线是被代理服务器拒绝连接,这是怎么回事,又该如何解决呢?下面就由小编为大家带来代理连接服务器遭拒解决方法。火狐浏览器代理连接服务器失败怎么办第一步:打开火狐浏览器设置,搜索网络,打开网络设置第二步:勾选上不使用代理服务器,点击确定就可以了

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version