ByteBuddy拦截构造函数参数

问题描述

我正在尝试使用ByteBuddy和自定义构造函数动态创建一个类。 我已经读过Intercepting default constructor with Byte Buddy,并在此基础上编写了以下代码

Class<?> dynamicType = new ByteBuddy().subclass(Object.class,ConstructorStrategy.Default.NO_CONSTRUCTORS)
                .name("foo").defineConstructor(Modifier.PUBLIC).withParameters(int.class)
                .intercept(
                        to(new Object() {
                            public void construct() throws Exception {
                                System.out.println("before constructor");
                            }
                        })
                        .andThen(MethodCall.invoke(Object.class.getConstructor()))
                        .andThen(to(new Object() {
                            public void construct() throws Exception {
                                System.out.println("after constructor");
                            }})
                        ))
                .make()
                .load(Main.class.getClassLoader(),INJECTION)
                .getLoaded();

        dynamicType.getConstructor(int.class).newInstance(3);

我的问题是如何在调用超级构造函数之前和之后添加自定义代码中访问“ foo”构造函数的整数参数。

解决方法

当然,只需定义一个带有@Argument(0)注释的参数即可。

我建议不要使用匿名类,因为它们的程序包私有可见性可能会带来棘手的结果。