ByteBuddy:如何在另一个 class 中使用自定义方法声明一个 class
ByteBuddy: How to declare a class with a custom method inside another class
我正在尝试动态创建一个 class 来扩展 class ServerPing,在这个 class 中有一个名为 Serializer 的静态 class,我想覆盖它的方法 "a" 和 returns 我自己的 JsonElement。
问题是我不知道如何使用 bytebuddy 在另一个 class 中编辑静态 class。
它可能是这样的(但 defineClassInside 不存在):
Class<?> serverPingSerializerClone = new ByteBuddy()
.subclass(serverPingClass)
.defineClassInside("Serializer",
new ByteBuddy().subclass(ServerPing.Serializer.class)
.method(ElementMatchers.named("a")
.and(ElementMatchers.returns(JsonElement.class)
.and(ElementMatchers.takesArguments(3))))
.intercept(FixedValue.value(exampleResponse))
.make())
.make()
.load(Core.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();```
在字节码级别,在 Foo 中定义的内部 class Bar 只不过是一个 class 名为 Foo$Bar 和一些额外的元数据。
您可以像对待任何其他 class 一样对待 inner/nested class 和子class 它。如果你需要添加内部 class 元数据,Byte Buddy 有 DSL steps to edit/add 这样的信息,例如innerTypeOf.
我正在尝试动态创建一个 class 来扩展 class ServerPing,在这个 class 中有一个名为 Serializer 的静态 class,我想覆盖它的方法 "a" 和 returns 我自己的 JsonElement。 问题是我不知道如何使用 bytebuddy 在另一个 class 中编辑静态 class。
它可能是这样的(但 defineClassInside 不存在):
Class<?> serverPingSerializerClone = new ByteBuddy()
.subclass(serverPingClass)
.defineClassInside("Serializer",
new ByteBuddy().subclass(ServerPing.Serializer.class)
.method(ElementMatchers.named("a")
.and(ElementMatchers.returns(JsonElement.class)
.and(ElementMatchers.takesArguments(3))))
.intercept(FixedValue.value(exampleResponse))
.make())
.make()
.load(Core.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();```
在字节码级别,在 Foo 中定义的内部 class Bar 只不过是一个 class 名为 Foo$Bar 和一些额外的元数据。
您可以像对待任何其他 class 一样对待 inner/nested class 和子class 它。如果你需要添加内部 class 元数据,Byte Buddy 有 DSL steps to edit/add 这样的信息,例如innerTypeOf.