IT-迁哥
发布于 2024-01-25 / 107 阅读
22
0

jdk动态代理

记一次jdk通用动态代理的使用方法,使用匿名内部类会比较通用。

注(jdk只会代理接口的方法)

public class JdkCommonProxy {

    public Object getProxy(Object target) {
        return 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(method.getName());
                System.out.println("start");
                Object invoke = method.invoke(target, args);
                System.out.println("end");
                return invoke;
            }
        });

    }

    public static void main(String[] args) {
        HttpRequest httpRequest = (HttpRequest) new JdkCommonProxy().getProxy(new HttpRequestImpl());
        System.out.println(new JdkCommonProxy().getProxy(new HttpRequestImpl()) instanceof HttpRequest);

        System.out.println(new JdkCommonProxy().getProxy(new HttpRequestImpl()).getClass().getInterfaces()[0].getName());
        System.out.println(LocalDateTime.now().toString().replace("T", " "));
    }
}


评论