3

我有字符串和原始字节中的消息类型名称。如何通过这些材料创建 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);
4

1 回答 1

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);
    }
}
于 2013-04-12T05:58:01.330 回答