JAVA 静态代理和动态代理
参考文章:https://y4er.com/post/java-proxy/
一共讲两个,一个是静态代理,一个是动态代理!
静态代理
实现静态代理的前提:
1、代理类和被代理类实现了同一接口
2、被代理类需要实现具体继承接口中的方法
3、代理类调用的是具体类中的方法(也就是说代理类中需要接受一个被代理类的对象)
这里举的例子就是,供应商 - 微商 - 客户 之间的代理
供应商/微商的接口:
public interface Seller {
public void toSell();
}
供应商的实现类:
public class NormalSeller implements Seller{
@Override
public void toSell() {
System.out.println("我是卖鞋的!!!");
}
}
微商类的实现(这里体现的就是代理类):
public class MicroSeller implements Seller {
Seller normal = new NormalSeller();
@Override
public void toSell() {
this.go();
this.normal.toSell();
this.againgo();
}
public void go(){
System.out.println("瞧一瞧,看一看");
}
public void againgo(){
System.out.println("要不继续看看?");
}
}
这里Main如下:
public class Mymain {
public static void main(String[] args){
Seller testSeller = new MicroSeller();
testSeller.toSell();
}
}
那么以上是不是就通过静态代理,实现了微商类的代理类,因为我们在里面写了另外的两个方法go和againgo,通过这种静态代理模式,给了原本只有toSell方法就添加了两种方法,并且没有改变原来的类!
但是也有缺点:
1、每一种类型的真实类都需要一个代理类,代码量大
这个缺点怎么理解?比如下面,单纯写两个类型的静态代理,就需要创建如下类,过程繁琐

这里顺便扩展下知识,如果我们想要在原有的增删改查的操作上面,想要添加日志功能,那么我们又需要如何操作呢?



动态代理
如果我们通过动态代理的话,就可以帮助我们解决上面的问题!
动态代理和静态代理的唯一区别就在于:动态代理是将要代理的类进行动态生成的,省去为接口实现代理类的操作。
要使用动态代理的话,只需要将代理类继承InvocationHandler接口,然后实现其中的方法invoke即可!
那么静态代理中的代理类实现动态代理:
这里写的时候有个变动,就是之前说的代理类中需要接受一个被代理类的对象,现在这个被代理类的对象就作为代理类的构造函数的参数传入!
大家注意了,我们说过动态代理是将要代理的类进行动态生成的,省去为接口实现代理类的操作,所以我们现在就根本不需要再写相关的代理类和代理类的实现了,所以目前我们的代码就只有如下:
1、一个真实和代理共同的接口
2、真实类的实现
供应商/微商的接口:
public interface HostOperation {
public void toSell();
}
房东的实现类:
public class Host implements HostOperation {
private String hostName;
public Host(String hostName){
this.hostName = hostName;
}
@Override
public void toSell() {
System.out.println("房东出租房子...");
}
}
那么我们还需要实现能动态生成相关的代理类的一个类,这里就需要用到InvocationHandler这个接口类,具体原因下面继续讲述,先看如何代码实现
public class ProxyInvocationHandler implements InvocationHandler {
Object proxyTarget;
public ProxyInvocationHandler(Object proxyTarget){
this.proxyTarget = proxyTarget;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("瞧一瞧,看一看!!!");
if(method.getName().equals("toSell")){
try {
method.invoke(this.proxyTarget, args);
}catch (Exception e){
return null;
}
}
System.out.println("要不继续看看???");
return null;
}
}
运行代码:
public class Test {
public static void main(String[] args) {
Host host = new Host("小德房东");
InvocationHandler invocationHandler = new ProxyInvocationHandler(host);
// 动态生成代理类
HostOperation proxy = (HostOperation) Proxy.newProxyInstance(
Host.class.getClassLoader(),
new Class[]{HostOperation.class},
invocationHandler);
proxy.toSell();
}
}
结果图如下:

到这里可以发现最不同的地方就是不需要再去实现代理类对象的操作!
继续讲,通过动态代理就可以动态生成代理类,实现接口InvocationHandler的类(这个实现InvocationHandler的类相当于定义好被代理类的相关操作),最后然后通过Proxy类的newProxyInstance方法来生成动态代理类!
Proxy.newProxyInstance流程
那么继续思考,Proxy.newProxyInstance到底是怎么实现的,它为什么可以帮助我们实现自己想要实现的代理方法、语句等?
跟进去继续看newProxyInstance的源码实现(讲重点,主要自己看的太吃力了):
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
Objects.requireNonNull(h); //判断InvocationHandler实例h存在不存在,不存在则直接抛出异常
final Class<?>[] intfs = interfaces.clone(); //撒子玩意,盲猜 返回了Interface的class实例
final SecurityManager sm = System.getSecurityManager(); //得到系统管理器的实例
if (sm != null) { //判断系统管理器实例是否获得
checkProxyAccess(Reflection.getCallerClass(), loader, intfs); //检查权限,看了下getProxyClass0里面的注释,如果调用getProxyClass0方法就必须判断权限checkProxyAccess
}
/*
* Look up or generate the designated proxy class.
*/
Class<?> cl = getProxyClass0(loader, intfs); //获取代理类,里面是return proxyClassCache.get(loader, interfaces); ,这里注释有说明,
//如果你传入的loader定义的代理类有实现指定的接口的话,就通过WeakCache类的缓存中返回一个代理类,如果不是,就通过ProxyClassFactory来生成一个代理类
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl); //大概就是权限检测
}
final Constructor<?> cons = cl.getConstructor(constructorParams); //获取实现InvocationHandler接口的类的构造函数
final InvocationHandler ih = h; //接受了参数InvocationHandler h
if (!Modifier.isPublic(cl.getModifiers())) { //判断该类的修饰符是否为public属性
AccessController.doPrivileged(new PrivilegedAction<Void>() { //如果不是的话则改为public
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
return cons.newInstance(new Object[]{h}); //通过cons构造器创建一个对应的Class实例的对象
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}
这里继续看getProxyClass0中的方法:
如下显示,通过注释可以知道,如果传入的加载器定义的代理类实现给定的接口存在,这将简单地返回缓存副本,否则就使用ProxyClassFactory去生成这个代理类
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
// If the proxy class defined by the given loader implementing
// the given interfaces exists, this will simply return the cached copy;
// otherwise, it will create the proxy class via the ProxyClassFactory
return proxyClassCache.get(loader, interfaces);
}
ProxyClassFactory为如下:
private static final class ProxyClassFactory
implements BiFunction<ClassLoader, Class<?>[], Class<?>>
{
// prefix for all proxy class names
private static final String proxyClassNamePrefix = "$Proxy"; //代理类对象的前缀名 $Proxy
// next number to use for generation of unique proxy class names
private static final AtomicLong nextUniqueNumber = new AtomicLong(); //用于生成唯一代理类名的下一个编号
@Override
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
for (Class<?> intf : interfaces) {
/*
* Verify that the class loader resolves the name of this
* interface to the same Class object.
*/
Class<?> interfaceClass = null;
try {
interfaceClass = Class.forName(intf.getName(), false, loader); //通过指定loader加载器生成指定类,如果没有找到指定的类则抛出异常
} catch (ClassNotFoundException e) {
}
if (interfaceClass != intf) { //如果加载的interfaceClass跟intf不一致则抛出异常
throw new IllegalArgumentException(
intf + " is not visible from class loader");
}
/*
* Verify that the Class object actually represents an
* interface.
*/
if (!interfaceClass.isInterface()) {//验证类对象是否表示同一个接口
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* Verify that this interface is not a duplicate.
*/
if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) { //判断接口是否是重复的
throw new IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
}
String proxyPkg = null; // package to define proxy class in
int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
/*
* Record the package of a non-public proxy interface so that the
* proxy class will be defined in the same package. Verify that
* all non-public proxy interfaces are in the same package.
*/
for (Class<?> intf : interfaces) {
int flags = intf.getModifiers();
if (!Modifier.isPublic(flags)) {
accessFlags = Modifier.FINAL;
String name = intf.getName();
int n = name.lastIndexOf('.');
String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
if (proxyPkg == null) {
proxyPkg = pkg;
} else if (!pkg.equals(proxyPkg)) {
throw new IllegalArgumentException(
"non-public interfaces from different packages");
}
}
}
if (proxyPkg == null) {
// if no non-public proxy interfaces, use com.sun.proxy package
proxyPkg = ReflectUtil.PROXY_PACKAGE + "."; // "com.sun.proxy." 字符串进行拼接
}
/*
* Choose a name for the proxy class to generate.
*/
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num; // 拼接要生成代理类的名称, com.sun.proxy.$Proxy0/1/2/3
/*
* Generate the specified proxy class.
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags); //获取要生成类class的字节码
try {
return defineClass0(loader, proxyName, proxyClassFile, 0, proxyClassFile.length); //通过反射defineClass0生成一个指定的Class类实例
} catch (ClassFormatError e) {
/*
* A ClassFormatError here means that (barring bugs in the
* proxy class generation code) there was some other
* invalid aspect of the arguments supplied to the proxy
* class creation (such as virtual machine limitations
* exceeded).
*/
throw new IllegalArgumentException(e.toString());
}
}
}
运行如下代码:
public class MyMain {
public static void main(String[] args){
Seller normal = new NormalSeller();
InvocationHandler invocationHandler = new MicroSeller(normal);
Seller microSeller = (Seller)Proxy.newProxyInstance(
Seller.class.getClassLoader(),
new Class[]{Seller.class},
invocationHandler);
microSeller.toSell();
System.out.println(microSeller.getClass().getName());
}
}
最终获取的类名为如下显示:

那么其实也就是Proxy.newInstance()反射动态生成了一个对应的代理类返回,并且该类的名称还是com.sun.proxy.$Proxy0/1/2/3递增的!

浙公网安备 33010602011771号