当前位置: 移动技术网 > IT编程>开发语言>Java > 深度剖析java动态静态代理原理源码

深度剖析java动态静态代理原理源码

2019年07月19日  | 移动技术网IT编程  | 我要评论

正文

关于java中的动态代理,我们首先需要了解的是一种常用的设计模式--代理模式,而对于代理,根据创建代理类的时间点,又可以分为静态代理和动态代理。

静态代理
1、静态代理

静态代理:由程序员创建或特定工具自动生成源代码,也就是在编译时就已经将接口,被代理类,代理类等确定下来。在程序运行之前,代理类的.class文件就已经生成。

2、静态代理简单实现

根据上面代理模式的类图,来写一个简单的静态代理的例子。我这儿举一个比较粗糙的例子,假如一个班的同学要向老师交班费,但是都是通过班长把自己的钱转交给老师。这里,班长就是代理学生上交班费,

班长就是学生的代理。

首先,我们创建一个person接口。这个接口就是学生(被代理类),和班长(代理类)的公共接口,他们都有上交班费的行为。这样,学生上交班费就可以让班长来代理执行。

/**
* 创建person接口
* @author chenhao
*/
public interface person {
//上交班费
void givemoney();
}

student类实现person接口。student可以具体实施上交班费的动作。

public class student implements person {
private string name;
public student(string name) {
this.name = name;
}
@override
public void givemoney() {
system.out.println(name + "上交班费50元");
}
}

studentsproxy类,这个类也实现了person接口,但是还另外持有一个学生类对象,由于实现了peson接口,同时持有一个学生对象,那么他可以代理学生类对象执行上交班费(执行givemoney()方法)行为。

/**
* 学生代理类,也实现了person接口,保存一个学生实体,这样既可以代理学生产生行为
* @author chenhao
*
*/
public class studentsproxy implements person{
//被代理的学生
student stu;
public studentsproxy(student stu) {
this.stu = stu;
}
//代理上交班费,调用被代理学生的上交班费行为
public void givemoney() {
stu.givemoney();
}
}

下面测试一下,看如何使用代理模式:

public class staticproxytest {
public static void main(string[] args) {
//被代理的学生张三,他的班费上交有代理对象monitor(班长)完成
student zhangsan = new student("张三");
//生成代理对象,并将张三传给代理对象
person monitor = new studentsproxy(zhangsan);
//班长代理上交班费
monitor.givemoney();
}
}

运行结果:

这里并没有直接通过张三(被代理对象)来执行上交班费的行为,而是通过班长(代理对象)来代理执行了。这就是代理模式。

代理模式最主要的就是有一个公共接口(person),一个具体的类(student),一个代理类(studentsproxy),代理类持有具体类的实例,代为执行具体类实例方法。上面说到,代理模式就是在访问实际对象时引入一定程度的间接性,因为这种间接性,可以附加多种用途。这里的间接性就是指不直接调用实际对象的方法,那么我们在代理过程中就可以加上一些其他用途。就这个例子来说,加入班长在帮张三上交班费之前想要先反映一下张三最近学习有很大进步,通过代理模式很轻松就能办到:

这里并没有直接通过张三(被代理对象)来执行上交班费的行为,而是通过班长(代理对象)来代理执行了。这就是代理模式。

代理模式最主要的就是有一个公共接口(person),一个具体的类(student),一个代理类(studentsproxy),代理类持有具体类的实例,代为执行具体类实例方法。上面说到,代理模式就是在访问实际对象时引入一定程度的间接性,因为这种间接性,可以附加多种用途。这里的间接性就是指不直接调用实际对象的方法,那么我们在代理过程中就可以加上一些其他用途。就这个例子来说,加入班长在帮张三上交班费之前想要先反映一下张三最近学习有很大进步,通过代理模式很轻松就能办到:

/**
* 学生代理类,也实现了person接口,保存一个学生实体,这样既可以代理学生产生行为
* @author chenhao
*
*/
public class studentsproxy implements person{
//被代理的学生
student stu;
public studentsproxy(student stu) {
this.stu = stu;
}
//代理上交班费,调用被代理学生的上交班费行为
public void givemoney() {
system.out.println("张三最近学习有进步!");
stu.givemoney();
}
}

模式优缺点

优点

1、代理模式能够协调调用者和被调用者,在一定程度上降低了系统的耦合度。

2、代理对象可以在客户端和目标对象之间起到中介的作用,这样起到了的作用和保护了目标对象的

缺点

1、由于在客户端和真实主题之间增加了代理对象,因此有些类型的代理模式可能会造成请求的处理速度变慢。
2、实现代理模式需要额外的工作,有些代理模式的实现非常复杂。

动态代理

1.动态代理

前面介绍了静态代理,虽然静态代理模式很好用,但是静态代理还是存在一些局限性的,比如使用静态代理模式需要程序员手写很多代码,这个过程是比较浪费时间和精力的。一旦需要代理的类中方法比较多,或者需要同时代理多个对象的时候,这无疑会增加很大的复杂度。

代理类在程序运行时创建的代理方式被成为动态代理。 我们上面静态代理的例子中,代理类(studentproxy)是自己定义好的,在程序运行之前就已经编译完成。然而动态代理,代理类并不是在java代码中定义的,而是在运行时根据我们在java代码中的“指示”动态生成的。相比于静态代理, 动态代理的优势在于可以很方便的对代理类的函数进行统一的处理,而不用修改每个代理类中的方法。

2、动态代理简单实现

在java的java.lang.reflect包下提供了一个proxy类和一个invocationhandler接口,通过这个类和这个接口可以生成jdk动态代理类和动态代理对象。

public class dynamicproxytest {
interface ihello {
void sayhello();
}
static class hello implements ihello {
@override
public void sayhello() {
system.out.println("hello world");
}
}
static class dynamicproxy implements invocationhandler {
object originalobj;
object bind(object originalobj) {
this.originalobj = originalobj;
return proxy.newproxyinstance(originalobj.getclass().getclassloader(), originalobj.getclass().getinterfaces(), this);
}
/**
*object proxy是代理的对象, method method是真实对象中调用方法的method类, object[] args是真实对象中调用方法的参数
*/
@override
public object invoke(object proxy, method method, object[] args) throws throwable {
system.out.println("welcome");
return method.invoke(originalobj, args);
}
}
public static void main(string[] args) {
ihello hello = (ihello) new dynamicproxy().bind(new hello());
hello.sayhello();
}
}

运行结果如下:

welcome 
hello world

动态代理原理分析

上面说到,动态代理的优势在于可以很方便的对代理类的函数进行统一的处理,而不用修改每个代理类中的方法。是因为所有被代理执行的方法,都是通过在invocationhandler中的invoke方法调用的,所以我们只要在invoke方法中统一处理,就可以对所有被代理的方法进行相同的操作了。上述代码里,唯一的“黑厘子”就是proxy.newproxyinstance()方法,除此之外再没有任何特殊之处。

在jdk动态代理中涉及如下角色:

业务接口interface、业务实现类target、业务处理类handler、jvm在内存中生成的动态代理类$proxy0

动态代理原理图:

说白了,动态代理的过程是这样的:

1.proxy通过传递给它的参数(interfaces/invocationhandler)生成代理类$proxy0;

2.proxy通过传递给它的参数(classloader)来加载生成的代理类$proxy0的字节码文件;

动态代理的关键代码就是proxy.newproxyinstance(classloader, interfaces, handler),我们跟进源代码看看

public static object newproxyinstance(classloader loader, class<?>[] interfaces, invocationhandler h) throws illegalargumentexception {
  // handler不能为空
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.
*/
  // 通过loader和接口,得到代理的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());
}
}

我们看一下newinstance方法的源代码:

private static object newinstance(constructor<?> cons, invocationhandler h) {
try {
return cons.newinstance(new object[] {h} );
} catch (illegalaccessexception | instantiationexception e) {
throw new internalerror(e.tostring());
} catch (invocationtargetexception e) {
throwable t = e.getcause();
if (t instanceof runtimeexception) {
throw (runtimeexception) t;
} else {
throw new internalerror(t.tostring());
}
}
}

讲解完了代理类的生成源码,我们一定想要看看代理类的代码是什么样的,下面提供一个生成代理类的方法供大家使用:

/**
* 代理类的生成工具 
* @author chenhao
* @since 2019-4-2 
*/
public class proxygeneratorutils {
/**
* 把代理类的字节码写到硬盘上 
* @param path 保存路径 
*/
public static void writeproxyclasstoharddisk(string path) {
// 第一种方法
// system.getproperties().put("sun.misc.proxygenerator.savegeneratedfiles", true); 
// 第二种方法 
// 获取代理类的字节码 
byte[] classfile = proxygenerator.generateproxyclass("$proxy11", userserviceimpl.class.getinterfaces());
fileoutputstream out = null;
try {
out = new fileoutputstream(path);
out.write(classfile);
out.flush();
} catch (exception e) {
e.printstacktrace();
} finally {
try {
out.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
}
public static void main(string[] args) {
proxygeneratorutils.writeproxyclasstoharddisk("c:/x/$proxy11.class");
}
} 

此时就会在指定的c盘x文件夹下生成代理类的.class文件,我们看下反编译后的结果:

package org.fenixsoft.bytecode;
import java.lang.reflect.invocationhandler;
import java.lang.reflect.method;
import java.lang.reflect.proxy;
import java.lang.reflect.undeclaredthrowableexception;
public final class $proxy0 extends proxy
implements dynamicproxytest.ihello
{
private static method m3;
private static method m1;
private static method m0;
private static method m2;
/**
*注意这里是生成代理类的构造方法,方法参数为invocationhandler类型,看到这,是不是就有点明白
*super(paraminvocationhandler),是调用父类proxy的构造方法。
*父类持有:protected invocationhandler h;
*proxy构造方法:
* protected proxy(invocationhandler h) {
* objects.requirenonnull(h);
* this.h = h;
* }
*
*/
public $proxy0(invocationhandler paraminvocationhandler)
throws 
{
super(paraminvocationhandler);
}
/**
* 
*这里调用代理对象的sayhello方法,直接就调用了invocationhandler中的invoke方法,并把m3传了进去。
*this.h.invoke(this, m3, null); this.h就是父类proxy中保存的invocationhandler实例变量
*来,再想想,代理对象持有一个invocationhandler对象,invocationhandler对象持有一个被代理的对象,
*再联系到invacationhandler中的invoke方法。嗯,就是这样。
*/
public final void sayhello()
throws 
{
try
{
this.h.invoke(this, m3, null);
return;
}
catch (runtimeexception localruntimeexception)
{
throw localruntimeexception;
}
catch (throwable localthrowable)
{
throw new undeclaredthrowableexception(localthrowable);
}
}
// 此处由于版面原因,省略equals()、hashcode()、tostring()三个方法的代码
// 这3个方法的内容与sayhello()非常相似。
static
{
try
{
m3 = class.forname("org.fenixsoft.bytecode.dynamicproxytest$ihello").getmethod("sayhello", new class[0]);
m1 = class.forname("java.lang.object").getmethod("equals", new class[] { class.forname("java.lang.object") });
m0 = class.forname("java.lang.object").getmethod("hashcode", new class[0]);
m2 = class.forname("java.lang.object").getmethod("tostring", new class[0]);
return;
}
catch (nosuchmethodexception localnosuchmethodexception)
{
throw new nosuchmethoderror(localnosuchmethodexception.getmessage());
}
catch (classnotfoundexception localclassnotfoundexception)
{
throw new noclassdeffounderror(localclassnotfoundexception.getmessage());
}
}
}

这个代理类的实现代码也很简单,它为传入接口中的每一个方法,以及从 java.lang.object中继承来的equals()、hashcode()、tostring()方法都生成了对应的实现 ,并且统一调用了invocationhandler对象的invoke()方法(代码中的“this.h”就是父类proxy中保存的invocationhandler实例变量)来实现这些方法的内容,各个方法的区别不过是传入的参数和method对象有所不同而已,所以无论调用动态代理的哪一个方法,实际上都是在执行invocationhandler.invoke()中的代理逻辑。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网