Reputation: 919
I'm trying to dynamically create a class which extends a class ServerPing, inside this class there is a static class called Serializer, I want to override its method "a" and returns my own JsonElement. The problem is that I don't know how to edit a static class inside another class using bytebuddy.
Here is what it could look like (but defineClassInside doesn't exist):
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();```
Upvotes: 1
Views: 704
Reputation: 44032
At the byte code level, an inner class Bar defined inside Foo is nothing but a class named Foo$Bar with some additional meta data.
You can just treat the inner/nested class like any other class and subclass it. If you need to add inner class meta data, Byte Buddy has DSL steps to edit/add such information, e.g. innerTypeOf.
Upvotes: 2