如何通过给定的消息类型名称和原始字节来获取Java Object的protobuf?

时间:2013-04-12 05:39:12

标签: java protocol-buffers

我在字符串和原始字节中有消息类型名称。如何通过这些材料创建java对象? b.proto

pakage foo;
message Bar {
 required int32 id = 1;
 required string name = 2;
}

TestMain.java

foo.Bar bar = foo.Bar.newBuilder()
.setId(1).setName("foobar").build();
byte[] rawbytes = bar.toByteArray();
String typeName = bar.getDescriptorForType().getFullName();

foo.Bar b = (foo.Bar) howTo(rawbyte, typeName);

1 个答案:

答案 0 :(得分:5)

正如我在评论中所说,对我来说这似乎毫无意义,但你可以轻易地使用反思:

public static Object parseDynamic(String type, byte[] bytes) {
    try {
        Class<?> clazz = Class.forName(type);
        Method method = clazz.getDeclaredMethod("parseFrom", byte[].class);
        return method.invoke(null, bytes);
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException("Non-message type", e);
    } catch (IllegalAccessException e) {
        throw new IllegalArgumentException("Non-message type", e);
    } catch (InvocationTargetException e) {
        // TODO: Work out what exactly you want to do.
        throw new IllegalArgumentException("Bad data?", e);
    }
}