gpt4 book ai didi

java - 在Byte Buddy中设置一个instanceField

转载 作者:太空宇宙 更新时间:2023-11-04 12:28:20 24 4
gpt4 key购买 nike

我正在尝试弄清楚如何使用 Byte Buddy 设置实例字段的值。文档说:

Always remember to assign a value to this field before calling methods on an instance of such a dynamic class. Otherwise, a method delegation will result in a NullPointerException.

但我在文档或单元测试中没有看到如何执行此操作的任何地方。

我的动态类是:

new ByteBuddy().subclass(AbstractService.class)
.name(serviceName)
.method(ElementMatchers.named("start").and(
ElementMatchers.takesArguments(0)))
.intercept(
MethodDelegation.toInstanceField(service, "consumer")
.filter(ElementMatchers.isAnnotatedWith(Start.class)))
.method(ElementMatchers.named("stop").and(
ElementMatchers.takesArguments(0)))
.intercept(
MethodDelegation.to(instance).filter(
ElementMatchers.isAnnotatedWith(Stop.class)))
.make();

我看到另一篇文章,其中包含拦截任何构造函数并将 @FieldProxyMethodDelegation 结合使用的答案,但我不知道如何做到这一点。我在 .constructor(ElementMatchers.any()).intercept(...) 的某些变体的结果方面尝试过的所有方法都会导致:

java.lang.IllegalArgumentException: None of [] allows for delegation from...

最佳答案

基本上,当您使用MethodDelegation.toInstanceField时,Byte Buddy 将给定名称的字段添加到生成的类中。在您的例子中,Byte Buddy 添加了一个类型为 service 的字段。命名"consumer" .

您现在需要决定如何为此字段分配值,因为该字段没有值,即 null在分配之前。如果您调用了带有 @Start 注解的方法在此之前,您会遇到 NullPointerException .

分配字段的最简单方法是反射。类型安全的替代方案是实现一些接口(interface)

interface SetterIFace {
void setConsumer(MyType myType);
}

鉴于您的 service类型是 Class<MyType> 。然后您可以添加:

.implement(SetterIFace.class).intercept(FieldAccessor.ofBeanProperty())

实现SetterIFaceMethodDelegation 中定义该字段后,作为该字段的 setter .

关于java - 在Byte Buddy中设置一个instanceField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38150470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com