vendredi 14 avril 2023

How do I extract methods from a class object to use in a lambda expression?

I have a section of code that looks like this, repeated several times:

net.messageBuilder(AddLingeringEffectS2CPacket.class, id(), NetworkDirection.PLAY_TO_CLIENT)
    .decoder((buf) -> new AddLingeringEffectS2CPacket(buf))
    .encoder((msg, buf) -> msg.toBytes(buf))
    .consumer((msg, ctx) -> msg.handle(ctx))
    .add();

This is a lot of boilerplate. I figured I could create a method that just takes in the class reference, the id, and the NetworkDirection, and from there I could extract the constructor and the methods from the class object to reduce said boilerplate. This looks like:

private static <MSG extends IMessage> void buildMessage(Class<MSG> clazz, int id, NetworkDirection direction)
{
    INSTANCE.messageBuilder(clazz, id, direction)
            .decoder(buf ->
            {
                return clazz.getConstructor(FriendlyByteBuf.class).newInstance(buf);
            })
            .encoder((msg, buf) ->
            {
                clazz.getMethod("toBytes", FriendlyByteBuf.class).invoke(msg, buf);
            })
            .consumer((msg, ctx) ->
            {
                clazz.getMethod("handle", Supplier.class).invoke(msg, ctx);
            });
}

(Omitted a bunch of try/catches for clarity, a lack of exception handling definitely isn't the issue.)

Unfortunately, the library I'm working with (Minecraft Forge's Simpleimpl networking system) throws some very undescriptive errors at runtime whenever this code's hit, so I'm lost as to what exactly's wrong.

Invalid message AddLingeringEffectS2CPacket




Aucun commentaire:

Enregistrer un commentaire