- 第一种:
Class clazzProxy=Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
//得到其有参的构造方法
Constructor con=clazzProxy.getConstructor(InvocationHandler.class);
//创建一个内部类,该类为上面所得方法的的参数类
class MyInvocationHandler implements InvocationHandler{
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
return null;
}
}
con.newInstance(new MyInvocationHandler());
- 第二种
//获得Collection代理类
Class clazzProxy=Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
//把参数定义成匿名内部类
con.newInstance(new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
return null;
}
});
- 第三种
//第三中获得代理类实例的方法---直接用Proxy类的静态方法,来获得其代理类的实例
Collection proxy=(Collection)Proxy.newProxyInstance(
Collection.class.getClassLoader(),
new Class[]{Collection.class},
new InvocationHandler(){
ArrayList target=new ArrayList();
@Override
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
// TODO Auto-generated method stub
Object obj=method.invoke(target, args);
return obj;
}
}
);