【问题标题】:creating Java Proxy instance for a class type?为类类型创建 Java 代理实例?
【发布时间】:2013-01-11 11:49:54
【问题描述】:

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

    // 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。在检查他们的源代码之前,任何人都可以指出需要做什么来代理具体的类类型,而不仅仅是接口?

【问题讨论】:

    标签: java easymock proxy-classes


    【解决方案1】:

    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" });
    

    【讨论】:

    • 那么 OP 的问题是:CGLIB 如何在纯 Java 方面做到这一点 :)
    • @GiovanniAzua 它使用 ASM 字节码操作库为代理子类动态生成字节码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多