第一种:
//获取动态类的字节码文件
Class clazzProxy = Proxy.getProxyClass(类加载器Collection.class.getClassLoder,接口Collection.class);
//获取动态类的构造方法(带参数),动态类无不带参构造
Constructor constructor = clazzProxy.getConstructor(InvocationHandler.class);
//调用构造方法,参数为InvocationHandler接口的实现类对象
//MyInvocationhandler为实现InvocationHandler接口的类作为参数传入
Collection proxy = (Collection) constructor.newInstance(new MyInvocationhandler());
//因为动态类实现了Collection,所以是Collection类型
System.out.println(proxy);
第二种:
Collection proxy2 = (Collection) constructor .newInstance(new InvocationHandler() {
public Object invoke(Object proxy, Method method,Object[] args) throws Throwable {
return null;
}
});
// 这种方式同第一种类似,只不过是将参数换成实现InvocationHandler接口的子类,而且是匿名内部类
第三种:
//Proxy的静态方法newProxyInstance,public static Object newProxyInstance(ClassLoader loader,
// Class<?>[] interfaces,
// InvocationHandler h)
final ArrayList target=new ArrayList();
Collection proxy3 = (Collection) Proxy.newProxyInstance(
Collection.class.getClassLoader(),
new Class[] { Collection.class },
new InvocationHandler() {
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
retObj = method.invoke(target, args);
return retObj;
}
});
proxy3.add("abcd");
System.out.println(proxy3); |
|