简体   繁体   中英

ByteBuddy: How to declare a class with a custom method inside another class

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();```

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, eg innerTypeOf.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM