当前位置:首页 > CN2资讯 > 正文内容

Java 动态代理java静态代理和动态代理

3天前CN2资讯
Java的动态代理

例子:

1.Subject接口

public interface Subject {

    public void doSomething();

    public void callHome();

}

2.Subject的实现类RealSubject

public class RealSubject implements Subject {

    public void doSomething() {

        System.out.println("call doSomething()");

    }

    public void callHome() {

        System.out.println("call home");

    }

}

3.动态代理类DynamicProxy

import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Method;

import java.lang.reflect.Proxy;

public class DynamicProxy implements InvocationHandler {

    private Object proxied;

    public DynamicProxy(Object proxied) {

        this.proxied = proxied;

    }

    @SuppressWarnings("unchecked")

    public <T> T getProxy() {

        return (T) Proxy.newProxyInstance(proxied.getClass().getClassLoader(),

                proxied.getClass().getInterfaces(), this);

    }

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

            throws Throwable {

        beforeMethod();

        Object object = method.invoke(proxied, args);

        afterMethod();

        return object;

    }

    public void beforeMethod() {

        System.out.println("before");

    }

    public void afterMethod() {

        System.out.println("after");

    }

}

4.测试类

public class Test {

    public static void main(String args[]) {

        Subject proxySubject = new DynamicProxy(new RealSubject()).getProxy();

        proxySubject.doSomething();

        System.out.println("");

        proxySubject.callHome();

    }

}

测试结果

before

call doSomething()

after

before

call home

after

动态代理的JDK官方文档说明

java.lang.reflect.Proxy

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

A dynamic proxy class (simply referred to as a proxy class below) is a class that implements a list of interfaces specified at runtime when the class is created, with behavior as described below. A proxy interface is such an interface that is implemented by a proxy class. A proxy instance is an instance of a proxy class. Each proxy instance has an associated invocation handler object, which implements the interface InvocationHandler. A method invocation on a proxy instance through one of its proxy interfaces will be dispatched to the invoke method of the instance's invocation handler, passing the proxy instance, a java.lang.reflect.Method object identifying the method that was invoked, and an array of type Object containing the arguments. The invocation handler processes the encoded method invocation as appropriate and the result that it returns will be returned as the result of the method invocation on the proxy instance.

java.lang.reflect.InvocationHandler

InvocationHandler is the interface implemented by the invocation handler of a proxy instance.

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

Proxy部分JDK源码

private Proxy() {

}

protected Proxy(InvocationHandler h) {

doNewInstanceCheck();

this.h = h;

}

由于 Proxy 内部从不直接调用构造函数,所以 private 类型意味着禁止任何调用 由于 Proxy 内部从不直接调用构造函数,所以 protected 意味着只有子类可以调用

public static Object newProxyInstance(ClassLoader loader,

Class<?>[] interfaces,

InvocationHandler h)

throws IllegalArgumentException

{

if (h == null) {

throw new NullPointerException();

}

final Class<?>[] intfs = interfaces.clone();

final SecurityManager sm = System.getSecurityManager();

if (sm != null) {

checkProxyAccess(Reflection.getCallerClass(), loader, intfs);

}

/*

* Look up or generate the designated proxy class.

*/

Class<?> cl = getProxyClass0(loader, intfs);

/*

* Invoke its constructor with the designated invocation handler.

*/

try {

final Constructor<?> cons = cl.getConstructor(constructorParams);

final InvocationHandler ih = h;

if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(cl)) {

// create proxy instance with doPrivilege as the proxy class may

// implement non-public interfaces that requires a special permission

return AccessController.doPrivileged(new PrivilegedAction<Object>() {

public Object run() {

return newInstance(cons, ih);

}

});

} else {

return newInstance(cons, ih);

}

} catch (NoSuchMethodException e) {

throw new InternalError(e.toString());

}

}

一个典型的动态代理创建对象过程可分为以下四个步骤:
1、通过实现InvocationHandler接口创建自己的调用处理器 IvocationHandler handler = new InvocationHandlerImpl(...);
2、通过为Proxy类指定ClassLoader对象和一组interface创建动态代理类
Class clazz = Proxy.getProxyClass(classLoader,new Class[]{...});
3、通过反射机制获取动态代理类的构造函数,其参数类型是调用处理器接口类型
Constructor constructor = clazz.getConstructor(new Class[]{InvocationHandler.class});
4、通过构造函数创建代理类实例,此时需将调用处理器对象作为参数被传入
Interface Proxy = (Interface)constructor.newInstance(new Object[] (handler));
为了简化对象创建过程,Proxy类中的newInstance方法封装了2~4,只需两步即可完成代理对象的创建。
生成的ProxySubject继承Proxy类实现Subject接口,实现的Subject的方法实际调用处理器的invoke方法,而invoke方法利用反射调用的是被代理对象的的方法(Object result=method.invoke(proxied,args))

 

    你可能想看:

    扫描二维码推送至手机访问。

    版权声明:本文由皇冠云发布,如需转载请注明出处。

    本文链接:https://www.idchg.com/info/24372.html

    分享给朋友:

    “Java 动态代理java静态代理和动态代理” 的相关文章

    KVM是什么?深入了解KVM的定义、工作原理及应用场景

    KVM的定义与概念 谈到KVM时,首先想到的就是“键盘、显示器和鼠标”的组合,它让我们可以用一组设备控制多台计算机。这种技术非常适合在数据中心或需要远程管理的环境中使用。我对这个系统产生了兴趣,因为它显著提高了管理效率,节省了空间,还所有的操作都变得更简便。想象一下,如果有多台服务器,你需要同时监控...

    搬瓦工Plan v2:高性价比VPS套餐详解与用户指南

    搬瓦工Plan v2作为一个限量版VPS套餐,给很多用户带来了新的选择。与之前的The Plan套餐相比,Plan v2在配置与流量方面都实现了显著的提升。这款套餐不仅是一种实用的解决方案,也为不同需求的用户提供了灵活的选择。接下来,我将分享一些关于这个套餐的背景信息、主要升级点以及它适合哪些用户。...

    Hostwinds LLC:卓越的网络托管服务与高性价比优势

    Hostwinds LLC成立于2010年,位于美国西雅图。这家公司一直专注于提供多种网络托管服务,包括虚拟主机、虚拟专用服务器(VPS)和独立服务器。在这个竞争激烈的市场中,Hostwinds凭借其独特的优势和不断升级的服务赢得了客户的信赖。我个人认为,Hostwinds的历史反映了它对客户需求的...

    甲骨文云免费IPv6服务详解:轻松配置与应用技巧

    甲骨文云,作为一个综合性的云服务提供商,正迅速崛起于众多的云技术平台之中。它不仅拥有强大的数据处理能力,还提供了多种免费的云服务选项,让个人和企业都能以更低的成本探索并使用云计算的强大功能。首先,我对甲骨文云的快速适应能力和多种灵活服务感到印象深刻,尤其是它的免费套餐项目,吸引了不少用户前来试用。...

    Rackdog:高性价比的独立服务器租赁和托管解决方案

    Rackdog是一家充满活力的基础设施即服务(IaaS)提供商,成立于2020年。作为互联网时代的重要角色,Rackdog专注于独立服务器出租和托管业务,拥有一系列丰富的服务。通过自己的设备和网络架构,Rackdog正在为客户提供优质的托管解决方案。 Rackdog的AS号是AS398465,拥有多...

    获取美国住宅IP的全面指南:确保真实网络体验

    当我提到美国住宅IP地址时,脑海中总会浮现出那些连接到真正家庭网络的IP地址。这些地址并不是随便通过网络数组获取的,而是直接来源于美国的居民家庭网络。这样说来,我们可以简单理解为,美国住宅IP是一种具有真实家庭特征的网络身份。 美国住宅IP的定义并不是一个复杂的概念。它具有纯净度高、不易被识别为机器...