您的位置:首页 > 编程语言 > Java开发

java之动态代理

2017-10-31 01:54 302 查看

代理模式

说到动态代理,首先要明白什么是代理。代理模式一个对象不直接执行某个动作,而是有代理代未执行。举个例子超市里面卖糖果,超市作为一个代理

直接面向消费者,而糖果工厂不直接面向消费者,有超市代为执行卖糖果的动作。使用代码表示如下:

interface SugarProducer {
void sellSugar();
}

class SugarFactory implements SugarProducer {
public void sellSugar() {
System.out.println("sell sugar");
}
}

class SuperMarket implements SugarProducer {
SugarProducer sugarProducer;

public void setSugarProducer(SugarProducer sugarProducer) {
this.sugarProducer = sugarProducer;
}

@Override
public void sellSugar() {
sugarProducer.sellSugar() {
sugarProducer.sellSugar();
}
}
}


可以看出超市作为一个中间商即代理在从事卖糖果的动作。

什么是动态代理

动态代理类(以下称代理类)是实现了一组指定的接口的类,动代理类是在运行时动态创建的。

代理类实例即为代理类的实例。每个代理类实例关联了一个handler对象。invocation handler实现了InvocationHandler接口。

对代理实例的方法调用会被指派到代理实例的handler的invoke方法,并传入代理类实例、将被调用的方法(java.lang.reflect.Method)

和一个对象数组(方法参数)作为参数。

代理类有以下特征:

代理类是public, final, 并且是非抽象类

代理类的名字是未指定的,代理类的名字是以$Proxy开头

代理类继承了java.lang.reflect.Proxy

代理类确切的实现了指定的一组接口,接口的顺序是创建时传入的顺序

如果代理类实现的是非public接口,那么代理类将拥有和接口相同的命名空间。否则代理类没有指定的命名空间。

如果类是通过Proxy.getProxyClass()创建的或者实例通过Proxy.newInstance()创建的,那么Proxy.isProxyClass()方法返回true,否则false

The java.security.ProtectionDomain of a proxy class is the same as that of system classes loaded by the bootstrap class loader, such as java.lang.Object, because the code for a proxy class is generated by trusted system code. This protection domain will typically be granted java.security.AllPermission.

Each proxy class has one public constructor that takes one argument, an implementation of the interface InvocationHandler, to set the invocation handler for a proxy instance. Rather than having to use the reflection API to access the public constructor, a proxy instance can be also be created by calling the Proxy.newProxyInstance method, which combines the actions of calling Proxy.getProxyClass with invoking the constructor with an invocation handler.

创建代理类和实例

InvocationHandler handler = new InvocationHandler() {...}

Class proxyClass = Proxy.getProxyClass(Interface.class.getClassloader(), new Class[] {Interface.class});

Interface instance = proxyClass.getConstructor(new Class[] {InvocationHandler.class}).newInstance(new Object[]{handler});


代理类视图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java