p { margin-bottom: 0.21cm; }
得到动态代理的构造方法的字节码方法 :
Constructor constructor = clazzProxy1
.getConstructor(InvocationHandler. class );
创建动态代理需要传入一个 InvocationHandler InvocationHandler 是一个接口 我们需要定义一个类 实现该接口 然后在实例化动态代理类 MyInvocationHandler1 是实现了 InvocationHandler 接口的类
Collection proxy1 = (Collection) constructor
.newInstance( new MyInvocationHandler1());
创建动态类及实例对象需要做三个操作:
-
生成类中的方法有哪些 通过让其实现哪些接口类的方式告知
-
产生的类字节码必须有一个关联的类加载器对象
-
创建对象 创建对象时给他传递一个 InvocationHandler 参数进去
实现 InvocationHandler 接口的类有三种写法写法
用 Proxy. newProxyInstance () 创建实例对象可以将得到字节码,实例化实现 InvocationHandler 类的对象 创建 Proxy 对象溶为一体
-
得到字节码,创建实现 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());
-
创建实现 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 ;
}
});
-
将创建字节码和创建代理对象实例化对象 传递参都溶为一体
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;
}
});