ParserManager { @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> ByteBuf parse(T o){ for(RedisClientProtocol parser : parsers){ if(parser.supportes(o.getClass())){ Constructor constructor = getConstructor(parser.getClass(), o.getClass()); if(constructor == null){ logger.warn("[getOptionParser][support argument, but can not find constructor]{},{}", parser, o); continue; } RedisClientProtocol curParser; try { curParser = (RedisClientProtocol) constructor.newInstance(o); return curParser.format(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { logger.error("[getOptionParser][invocate constructor error]" + parser + "," + o, e); } } } throw new IllegalStateException("unknown parser for o:" + o.getClass()); }  @SuppressWarnings({ "unchecked", "rawtypes" }) static ByteBuf parse(T o); static List<RedisClientProtocol<?>> parsers; }
@Test public void test(){ Assert.assertEquals(":1\r\n", ByteBufUtils.readToString(ParserManager.parse(1L))); Assert.assertEquals("+nihao\r\n", ByteBufUtils.readToString(ParserManager.parse("nihao"))); Assert.assertEquals("-error\r\n", ByteBufUtils.readToString(ParserManager.parse(new RedisError("error")))); Assert.assertEquals("*2\r\n+str\r\n:1\r\n", ByteBufUtils.readToString(ParserManager.parse(new Object[]{"str", 1L}))); Assert.assertEquals("$5\r\nnihao\r\n", ByteBufUtils.readToString(ParserManager.parse(new ByteArrayOutputStreamPayload("nihao")))); int a = 1; Assert.assertEquals("*2\r\n+str\r\n:1\r\n", ByteBufUtils.readToString(ParserManager.parse(new Object[]{"str", a}))); }