jeudi 7 mai 2020

Better alternative to reflection than large switch statement using java 8

My old code create a FrameBody subclass based on identifier

Class<AbstractID3v2FrameBody> c = (Class<AbstractID3v2FrameBody> Class.forName("org.jaudiotagger.tag.id3.framebody.FrameBody" + identifier);
Class<?>[] constructorParameterTypes = {Class.forName("java.nio.ByteBuffer"), Integer.TYPE};
Object[] constructorParameterValues = {byteBuffer, frameSize};
Constructor<AbstractID3v2FrameBody> construct = c.getConstructor(constructorParameterTypes);
frameBody = (construct.newInstance(constructorParameterValues));

But profile analysis shows its a bit slow, the alternative to using reflecting is a big switch statement

switch(identifier)
{
    case ID3v24Frames.FRAME_ID_AUDIO_ENCRYPTION:

        frameBody = new FrameBodyAENC(byteBuffer, frameSize);
        break;

    case ID3v24Frames.FRAME_ID_ATTACHED_PICTURE:

        frameBody = new FrameBodyAPIC(byteBuffer, frameSize);
        break;

                .......
    }   

but I have over 100 identifiers, so its seems a bit cumbersome

Is there a more elegant way to do this in Java 8 ?





Aucun commentaire:

Enregistrer un commentaire