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

来源:互联网 发布:淘宝找人代付选项没了 编辑:程序博客网 时间:2024/05/21 16:56

p { margin-bottom: 0.21cm; }

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

Constructorconstructor = clazzProxy1

.getConstructor(InvocationHandler.class);

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

 

Collectionproxy1 = (Collection) constructor

.newInstance(newMyInvocationHandler1());

 

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

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

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

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

 

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

 

 

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

 

 

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

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

Constructorconstructor = clazzProxy1

.getConstructor(InvocationHandler.class);

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

classMyInvocationHandler1 implementsInvocationHandler {

 

@Override

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

throwsThrowable {

//TODOAuto-generated method stub

returnnull;

}

 

}

//实例化对象传递参数

Collectionproxy1 = (Collection) constructor

.newInstance(newMyInvocationHandler1());

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

 

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

Constructorconstructor = clazzProxy1

.getConstructor(InvocationHandler.class);

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

Collectionproxy2 = (Collection) constructor

.newInstance(newInvocationHandler() {

 

@Override

publicObject invoke(Object proxy, Method method,

Object[]args) throwsThrowable {

//TODOAuto-generated method stub

returnnull;

}

 

});

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

 

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

Collectionproxy3 = (Collection) Proxy.newProxyInstance(

Collection.class.getClassLoader(),newClass[]{Collection.class},

newInvocationHandler() {

 

@Override

publicObject invoke(Object proxy, Method method,

Object[]args) throwsThrowable {

ArrayListtarget = new ArrayList();

longbeginTime = System.currentTimeMillis();

ObjectreVal = method.invoke(target, args);

longendTime = System.currentTimeMillis();

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

returnreVal;

}

 

});

 

原创粉丝点击