11.2 创建动态代理实例即调用其方法

p { margin-bottom: 0.21cm; }

得到动态代理的构造方法的字节码方法 :

Constructor constructor = clazzProxy1

.getConstructor(InvocationHandler. class );

创建动态代理需要传入一个 InvocationHandler InvocationHandler 是一个接口 我们需要定义一个类 实现该接口 然后在实例化动态代理类 MyInvocationHandler1 是实现了 InvocationHandler 接口的类

 

Collection proxy1 = (Collection) constructor

.newInstance( new MyInvocationHandler1());

 

创建动态类及实例对象需要做三个操作:

  1. 生成类中的方法有哪些 通过让其实现哪些接口类的方式告知

  2. 产生的类字节码必须有一个关联的类加载器对象

  3. 创建对象 创建对象时给他传递一个 InvocationHandler 参数进去

 

实现 InvocationHandler 接口的类有三种写法写法

 

 

Proxy. newProxyInstance () 创建实例对象可以将得到字节码,实例化实现 InvocationHandler 类的对象 创建 Proxy 对象溶为一体

 

 

  1. 得到字节码,创建实现 InvocationHandler 接口的类 实例化对象 传递参数 全部分开写

// 得到构造方法的字节码

Constructor constructor = clazzProxy1

.getConstructor(InvocationHandler. class );

//2 创建实现 InvocationHandler 接口的类

class MyInvocationHandler1 implements InvocationHandler {

 

@Override

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

throws Throwable {

// TODO Auto-generated method stub

return null ;

}

 

}

// 实例化对象 传递参数

Collection proxy1 = (Collection) constructor

.newInstance( new MyInvocationHandler1());

  1. 创建实现 InvocationHandler 接口的类 实例化对象 传递参 合二为一 在实例化的时候创建实现 InvocationHandler 接口的类

 

// 得到构造方法的字节码

Constructor constructor = clazzProxy1

.getConstructor(InvocationHandler. class );

// 得到实例对象 在实例化的时候创建实现 InvocationHandler 接口的类

Collection proxy2 = (Collection) constructor

.newInstance( new InvocationHandler() {

 

@Override

public Object invoke(Object proxy, Method method,

Object[] args) throws Throwable {

// TODO Auto-generated method stub

return null ;

}

 

});

  1. 将创建字节码和创建代理对象实例化对象 传递参都溶为一体

 

System. out .println( " 第三种方式定义实例对象 将创建字节码和创建代理对象合二为一 " );

Collection proxy3 = (Collection) Proxy. newProxyInstance (

Collection. class .getClassLoader(), new Class[]{Collection. class },

new InvocationHandler() {

 

@Override

public Object invoke(Object proxy, Method method,

Object[] args) throws Throwable {

ArrayList target = new ArrayList();

long beginTime = System. currentTimeMillis ();

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

long endTime = System. currentTimeMillis ();

System. out .println(method.getName()+ " runing time" +(beginTime - endTime));

return reVal;

}

 

});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值