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

Sky*_*ker 7 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 */ });        
Run Code Online (Sandbox Code Playgroud)

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

Ian*_*rts 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" });
Run Code Online (Sandbox Code Playgroud)

  • @GiovanniAzua它使用ASM字节码操作库动态生成代理子类的字节码. (3认同)