如何用ByteBuddy动态扩展混凝土类

时间:2017-05-29 02:31:21

标签: java byte-buddy dynamic-proxy

我一直在玩ByteBuddy库一段时间,我发现自己陷入困境。当测试的类在同一个文件中(作为静态内部类)时,我有这个方法工作,但是现在我已经将逻辑分离成一个单独的文件,它已经不再工作了。

如果它有帮助(也许我采取了错误的方法),我的目标是创建输入类originalClazz的动态子类并存储对originalClazz Class对象的引用,以及对输入对象original的引用。 我使用ProxyHandler.execute方法直接调用original对象上的方法,并将返回值包装在代理中(也使用proxyMe)。

以下块在一个java文件中:

private static final String ORIGINAL_OBJECT_FIELD_NAME = "_original_object_";
private static final String ORIGINAL_CLASS_FIELD_NAME = "_original_class_";

public static <T> T proxyMe(final T original, final Class<?> originalClazz) {
    if (originalClazz != null && isNotFinal(originalClazz) && hasDefaultConstructor(originalClazz)) {
        try {
            final Class<?> newSubClass = new ByteBuddy()
                    .subclass(originalClazz, ConstructorStrategy.Default.NO_CONSTRUCTORS)
                    .defineField(ORIGINAL_OBJECT_FIELD_NAME, Object.class, Visibility.PUBLIC)
                    .defineField(ORIGINAL_CLASS_FIELD_NAME, Class.class, Visibility.PUBLIC)
                    .method(any())
                        .intercept(to(ProxyHandler.class))
                    .defineConstructor(Visibility.PUBLIC)
                        .intercept(MethodCall.invoke(originalClazz.getConstructor()))
                    .make()                                // <-- exception thrown here
                    .load(originalClazz.getClassLoader())
                    .getLoaded();

            final Object result = newSubClass.newInstance();
            setField(result, ORIGINAL_OBJECT_FIELD_NAME, original);
            setField(result, ORIGINAL_CLASS_FIELD_NAME, originalClazz);
            return (T) result;
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    return original;
}

public static class ProxyHandler {
    @RuntimeType
    public static Object execute(
        @SuperCall Callable<Object> callable,
        @This Object obj,
        @Origin Method method,
        @AllArguments Object[] arguments
    ) {
        ...
    }
}

在我的考试班......

@Test
public void makeProxy() throws Exception {
    final Foo foo = new Foo(new Bar("str"));
    proxyMe(foo, Foo.class);
}

public static class Bar {
    private String name;
    public Bar() {}
    public Bar(final String name) { this.name = name; }
    public String getName() { return name; }
}

public static class Foo {
    private Bar bar;
    public Foo() {}
    public Foo(final Bar bar) { this.bar = bar; }
    public Bar getBar() { return bar; }
}

抛出异常:

None of [
  TargetMethodAnnotationDrivenBinder.Record{
    ,
    candidate=public static java.lang.Object somepackage.Utils$ProxyHandler.execute(
      java.util.concurrent.Callable,
      java.lang.Object,
      java.lang.reflect.Method,
      java.lang.Object[]
    ),
    handlers=[
      TargetMethodAnnotationDrivenBinder.DelegationProcessor.Handler.Bound{
        parameterBinder=SuperCall.Binder.INSTANCE,
        annotation=@net.bytebuddy.implementation.bind.annotation.SuperCall(
          serializableProxy=false,
          nullIfImpossible=false,
          fallbackToDefault=true
        ),
        target=java.util.concurrent.Callable arg0,
        typing=Assigner.Typing.STATIC
      },
      TargetMethodAnnotationDrivenBinder.DelegationProcessor.Handler.Bound{
        parameterBinder=This.Binder.INSTANCE,
        annotation=@net.bytebuddy.implementation.bind.annotation.This(
          optional=false
        ),
        target=java.lang.Object arg1,
        typing=Assigner.Typing.STATIC
      },
      TargetMethodAnnotationDrivenBinder.DelegationProcessor.Handler.Bound{
        parameterBinder=Origin.Binder.INSTANCE,
        annotation=@net.bytebuddy.implementation.bind.annotation.Origin(
          cache=true
        ),
        target=java.lang.reflect.Method arg2,
        typing=Assigner.Typing.STATIC
      },
      TargetMethodAnnotationDrivenBinder.DelegationProcessor.Handler.Bound{
        parameterBinder=AllArguments.Binder.INSTANCE,
        annotation=
          @net.bytebuddy.implementation.bind.annotation.AllArguments(
            value=STRICT,
            includeSelf=false
          ),
        target=[Ljava.lang.Object; arg3, typing=Assigner.Typing.STATIC}],
        typing=Assigner.Typing.DYNAMIC
      }
    ]
    allows for delegation from public somepackage.UtilsTest$Bar somepackage.UtilsTest$Foo.getBar()

1 个答案:

答案 0 :(得分:1)

ProxyHandler班似乎是private。这可能意味着它对您的检测代码不可见,因此不能作为处理程序调用。让课程公开,一切都应该按预期工作。