Java动态代理之Proxy

引用自:http://blog.iluckymeeting.com/2018/01/06/javaproxy/

环境准备

  • 定义接口 Car、Truck
public interface Car {
    
    void start();

}

public interface Truck {

    void start();

    void stop();

    void pause();

}
  • 定义被代理的类
public class MyCar implements Car, Truck {

    @Override
    public void start() {
        System.out.println("MyCar start.");
    }

    @Override
    public void stop() {
        System.out.println("MyCar stop.");
    }

    @Override
    public void pause() {
        System.out.println("MyCar pause.");
    }
}
  • 创建InvocationHandler
public class MyInvocationHandler implements InvocationHandler {
    private Object target;

    public MyInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("MyInvocationHandler invoke begin.");

        Object ret = method.invoke(target, args);

        System.out.println("MyInvocationHandler invoke end.");

        return ret;
    }
}

创建代理类

现在开始给上面定义的MyCar类创建一个代理类,创建方式有两种。

  • 方式一,使用Proxy类的静态方法newProxyInstance
public class Server {
    public static void main(String[] args) {
        MyCar myCar = new MyCar();

        MyInvocationHandler myInvocationHandler = new MyInvocationHandler(myCar);

        Object proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), MyCar.class.getInterfaces(), myInvocationHandler);

        ((Car) proxy).start();
    }
}

运行main方法控制台输出了

MyInvocationHandler invoke begin.
MyCar start.
MyInvocationHandler invoke end.
  • 方式二,先获取代理类的定义,然后调用其构造方法实例化
public class Server {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        MyCar myCar = new MyCar();
        MyInvocationHandler myInvocationHandler = new MyInvocationHandler(myCar);

        Class<?> proxyClass = Proxy.getProxyClass(Thread.currentThread().getContextClassLoader(), MyCar.class.getInterfaces());
        Object proxy = proxyClass.getConstructor(InvocationHandler.class).newInstance(myInvocationHandler);
        ((Car) proxy).start();
    }
}

运行main方法,控制台输出了

MyInvocationHandler invoke begin.
MyCar start.
MyInvocationHandler invoke end.

代理类定义

接着上面的代码,生成代理类之后我们来打几行日志,看看代理类是个什么结构

  • 代理类的名称
System.out.println(proxy.getClass().getName());

运行main方法,控制台输出了

com.sun.proxy.$Proxy0

可见生成的代理类并没有指定的常规名称,而是采用了$Proxy0这样的名称,$Proxy这个前缀是Java为代理类保留的,我们自己命名类名的时候不要使用。

  • 代理类的继承结构
        System.out.println(proxy instanceof Proxy);
        System.out.println(proxy instanceof Car);
        System.out.println(proxy instanceof Truck);
        System.out.println(proxy instanceof MyCar);

控制台输出了

true
true
true
false

所以我们知道了,生成的代理类是接口Car、Truck的实现类,是Proxy类的子类,与被代理类之间没有继承关系。如果生成的代理类名称是$Proxy0,它的实现大概是这样的

public class $Proxy0 extends Proxy implements Car,Truck{
      ......
}
  • 代理类的位置

我们知道Java代码编译以后会生成对应的class字节码文件,那么代理类生成以后的class文件保存在哪里呢?或者说它所在的包是哪一个呢?前面输出代理类名称的时候已经出现过了

com.sun.proxy.$Proxy0

但是还有另外一种情况,当代理类实现的接口里有non-public声明时,代理类会生成到与接口相同的包里,这里我们把Car接口定义中的public关键字去掉,再次运行上面的代码,控制台输出变成了

com.myproxy.demo.$Proxy0

Car接口所在的包就是com.myproxy.demo

代理类的属性

  • ProtectionDomain
System.out.println(proxy.getClass().getProtectionDomain().getPermissions().toString());

控制台输出

java.security.Permissions@c39f790 (
 ("java.security.AllPermission" "<all permissions>" "<all actions>")
)

代理类的ProtectionDomain与Bootstrap ClassLoader加载的系统类相同,因为代理类的字节码文件是由受信任的系统代码生成的,所以被授予了AllPermission权限。

  • public or non-public

这里又分两种情况了,当代理类实现的接口都是public的时

        System.out.println(Modifier.isPublic(proxy.getClass().getModifiers()))
        System.out.println(Modifier.isFinal(proxy.getClass().getModifiers()));
        System.out.println(Modifier.isAbstract(proxy.getClass().getModifiers()));

控制台输出

true
true
false

如果把其中一个接口Car的public修饰符去掉,则控制台输出变成了

false
true
false

由此可以看出,代理类是final的、非abstract的,当实现的接口都是public的时,代理类是public的,一旦有接口是非public的,则代理类就会是非public的。

  • interfaces
        Class<?>[] interfaces = proxy.getClass().getInterfaces();
        for(Class<?> inter:interfaces){
            System.out.println(inter.getName());
        }

控制台会输出

com.myproxy.demo.Car
com.myproxy.demo.Truck
  • methods
        Method[] methods = proxy.getClass().getMethods();
        for(Method method:methods){
            System.out.println(method.getName());
        }

控制台输出了

equals
toString
hashCode
start
stop
pause
isProxyClass
getProxyClass
newProxyInstance
getInvocationHandler
wait
wait
wait
getClass
notify
notifyAll

start、stop、pause这几个方法好理解,是实现的Car接口和Truck接口的方法,其它几个方法应该是来自于Object这个Java大鸡肋(基类)。

  • 代理类的判断

Proxy类有一个静态方法可以判断一个类是否是代理类

System.out.println(Proxy.isProxyClass(proxy.getClass()));

控制台输出了

true
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,337评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,906评论 18 399
  • 1 场景问题# 1.1 访问多条数据## 考虑这样一个实际应用:要一次性访问多条数据。 这个功能的背景是这样的;在...
    七寸知架构阅读 8,114评论 1 52
  • 《超级演说家》第一期来了名叫李宁的选手。他身患残疾,却依然站上了这个舞台,用他残破的身体幽默的传达出他对生活的态度...
    方特三期阅读 3,964评论 1 1
  • 请一定要微笑面对生活~
    三日之城阅读 1,800评论 6 6