diff --git a/codec/src/main/java/io/netty/handler/codec/ByteToMessageCodec.java b/codec/src/main/java/io/netty/handler/codec/ByteToMessageCodec.java index cdd17a992e..8f3f205708 100644 --- a/codec/src/main/java/io/netty/handler/codec/ByteToMessageCodec.java +++ b/codec/src/main/java/io/netty/handler/codec/ByteToMessageCodec.java @@ -27,24 +27,25 @@ public abstract class ByteToMessageCodec extends ChannelHandlerAdapter implements ChannelInboundByteHandler, ChannelOutboundMessageHandler { - private final MessageToByteEncoder encoder = - new MessageToByteEncoder() { - @Override - public void encode( - ChannelHandlerContext ctx, - OUTBOUND_IN msg, ByteBuf out) throws Exception { - ByteToMessageCodec.this.encode(ctx, msg, out); - } - }; + private final MessageToByteEncoder encoder; + private final ByteToMessageDecoder decoder; - private final ByteToMessageDecoder decoder = - new ByteToMessageDecoder() { - @Override - public INBOUND_OUT decode( - ChannelHandlerContext ctx, ByteBuf in) throws Exception { - return ByteToMessageCodec.this.decode(ctx, in); - } - }; + protected ByteToMessageCodec(Class... encodableMessageTypes) { + encoder = new MessageToByteEncoder(encodableMessageTypes) { + @Override + protected void encode(ChannelHandlerContext ctx, OUTBOUND_IN msg, ByteBuf out) throws Exception { + ByteToMessageCodec.this.encode(ctx, msg, out); + } + }; + + decoder = new ByteToMessageDecoder() { + @Override + public INBOUND_OUT decode( + ChannelHandlerContext ctx, ByteBuf in) throws Exception { + return ByteToMessageCodec.this.decode(ctx, in); + } + }; + } @Override public ByteBuf newInboundBuffer( @@ -79,10 +80,10 @@ public abstract class ByteToMessageCodec encoder.freeOutboundBuffer(ctx); } - protected abstract void encode( - ChannelHandlerContext ctx, - OUTBOUND_IN msg, ByteBuf out) throws Exception; + protected boolean isEncodable(Object msg) throws Exception { + return encoder.isEncodable(msg); + } - protected abstract INBOUND_OUT decode( - ChannelHandlerContext ctx, ByteBuf in) throws Exception; + protected abstract void encode(ChannelHandlerContext ctx, OUTBOUND_IN msg, ByteBuf out) throws Exception; + protected abstract INBOUND_OUT decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception; }