如何在ByteBuddy中的类中添加字段并在方法拦截器中设置/获取该值 [英] How to add a field to a class in ByteBuddy and set / get that value in a method interceptor
问题描述
我正在使用字节伙伴在Ignite之上构建ORM,我们需要将一个字段添加到类中,然后在方法拦截器中对其进行访问。。
I am using byte-buddy to build an ORM on top of Ignite, we need to add a field to a class and then access it in a method interceptor..
所以这是一个示例,其中我向一个类中添加了一个字段
So here's an example where I add a field to a class
final ByteBuddy buddy = new ByteBuddy();
final Class<? extends TestDataEnh> clz = buddy.subclass(TestDataEnh.class)
.defineField("stringVal",String.class)
.method(named("setFieldVal")).intercept(
MethodDelegation.to(new SetterInterceptor())
)
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
final TestDataEnh enh = clz.newInstance();
enh.getFieldVal();
enh.setFieldVal();
System.out.println(enh.getClass().getName());
拦截器就是这样
public class SetterInterceptor {
@RuntimeType
public Object intercept() {
System.out.println("Invoked method with: ");
return null;
}
}
那么我如何获得新字段的值进入拦截器,以便我可以更改其值? (stringVal)
So how do I get the value of the new field into the interceptor so I can change it's value? (stringVal)
预先感谢
推荐答案
您可以使用 FieldProxy
以其名称访问字段。您需要先安装 FieldProxy.Binder
并将其注册在 MethodDdelegation
上,然后才能使用它,因为它需要自定义用于类型安全仪表的类型。 javadoc 解释了如何做到这一点。或者,您可以通过使用 @This
在实例上使用反射。 JVM在优化反射的使用方面非常有效。
You can use a FieldProxy
to access a field by its name. You need to install a FieldProxy.Binder
and register it on the MethodDdelegation
before you can use it as it requires a custom type for type-safe instrumentation. The javadoc explains how this can be done. Alternatively, you can use reflection on an instance by using @This
. The JVM is quite efficient in optimizing the use of reflection.
例如:
interface FieldGetter {
Object getValue();
}
interface FieldSetter {
void setValue(Object value);
}
public class SetterInterceptor {
@RuntimeType
public Object intercept(@FieldProxy("stringVal") FieldGetter accessor) {
Object value = accessor.getValue();
System.out.println("Invoked method with: " + value);
return value;
}
}
对于bean属性, FieldProxy
批注不需要显式名称,但可以从被拦截的getter或setter的名称中找到该名称。
For bean properties, the FieldProxy
annotation does not require an explicit name but discovers the name from the name of the intercepted getter or setter.
安装可以按照
MethodDelegation.to(SetterInterceptor.class)
.appendParameterBinder(FieldProxy.Binder.install(FieldGetter.class,
FieldSetter.class));
这篇关于如何在ByteBuddy中的类中添加字段并在方法拦截器中设置/获取该值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!