如何使用 cglib 生成带有自定义字段的代理?
How to generate proxy with custom field using cglib?
我正在使用 cglib 生成一些 class 的代理对象,我需要将一些客户字段绑定到代理对象,如下所示
String customFieldName = "myCustomField";
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(targetClass);
// What can I do to add custom field to the proxy class ?
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
// I'd access the custom field value here
Field field = obj.getClass().getField(customFieldName);
Object customFieldValue = field.get(obj);
// do something
return proxy.invokeSuper(obj, args);
}
});
当然,另一种方法是使用映射将值绑定到原始对象,但我不太喜欢这样做。
有人知道吗?
这在使用 cglib 时是不可能的,没有 API 除非您愿意访问底层 ASM API 以直接在字节代码中添加字段。如果您愿意更换工具,您可以使用 Byte Buddy,我维护的一个库:
Class<? extends TargetClass> proxy = new ByteBuddy()
.subclass(targetClass)
.method(any())
.intercept(MethodDelegation.to(MyInterceptor.class)
.andThen(SuperMethodCall.INSTANCE)
.defineField("myCustomField", Object.class, Visibility.PUBLIC)
.make()
.load(targetClass.getClassLoader())
.getLoaded();
class MyInterceptor {
static void intercept(@FieldValue("myCustomField") Object myCustomField) {
// do something
}
}
使用 cglib,您可以选择添加回调以使用回调 class.
为每个单独的代理委托给特定的增强器实例
我正在使用 cglib 生成一些 class 的代理对象,我需要将一些客户字段绑定到代理对象,如下所示
String customFieldName = "myCustomField";
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(targetClass);
// What can I do to add custom field to the proxy class ?
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
// I'd access the custom field value here
Field field = obj.getClass().getField(customFieldName);
Object customFieldValue = field.get(obj);
// do something
return proxy.invokeSuper(obj, args);
}
});
当然,另一种方法是使用映射将值绑定到原始对象,但我不太喜欢这样做。
有人知道吗?
这在使用 cglib 时是不可能的,没有 API 除非您愿意访问底层 ASM API 以直接在字节代码中添加字段。如果您愿意更换工具,您可以使用 Byte Buddy,我维护的一个库:
Class<? extends TargetClass> proxy = new ByteBuddy()
.subclass(targetClass)
.method(any())
.intercept(MethodDelegation.to(MyInterceptor.class)
.andThen(SuperMethodCall.INSTANCE)
.defineField("myCustomField", Object.class, Visibility.PUBLIC)
.make()
.load(targetClass.getClassLoader())
.getLoaded();
class MyInterceptor {
static void intercept(@FieldValue("myCustomField") Object myCustomField) {
// do something
}
}
使用 cglib,您可以选择添加回调以使用回调 class.
为每个单独的代理委托给特定的增强器实例