为类类型创建Java代理实例?

时间:2013-01-11 11:49:54

标签: java easymock proxy-classes

我有以下代码,用于为InvocationHandler实现支持的接口类型创建代理实例,但是当我使用具体的类类型时,它不起作用,这是众所周知的,记录在Proxy.newProxyInstance中:

    // NOTE: does not work because SomeConcreteClass is not an interface type
    final ClassLoader myClassLoader = SomeConcreteClass.getClassLoader();
    SomeConcreteClass myProxy = (SomeConcreteClass) Proxy.newProxyInstance(myClassLoader, new Class[] {
        SomeConcreteClass.class }, new InvocationHandler() { /* TODO */ });        

但是,如果我没记错的话,我已经在一些模拟框架中看到了这个用例,可以模拟一个具体的类类型,例如: EasyMock。在检查他们的源代码之前,任何人都可以指出需要做什么来代理具体的类类型而不仅仅是接口吗?

1 个答案:

答案 0 :(得分:12)

JDK动态代理仅适用于接口。如果要创建具有特定超类的代理,则需要使用类似CGLIB的内容。

Enhancer e = new Enhancer();
e.setClassLoader(myClassLoader);
e.setSuperclass(SomeConcreteClass.class);
e.setCallback(new MethodInterceptor() {
  public Object intercept(Object obj, Method method, Object[] args,
        MethodProxy proxy) throws Throwable {
    return proxy.invokeSuper(obj, args);
  }
});
// create proxy using SomeConcreteClass() no-arg constructor
SomeConcreteClass myProxy = (SomeConcreteClass)e.create();
// create proxy using SomeConcreteClass(String) constructor
SomeConcreteClass myProxy2 = (SomeConcreteClass)e.create(
    new Class<?>[] {String.class},
    new Object[] { "hello" });