Reputation: 219
I have message type name in string and raw bytes. how to create java object by these meterials? 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);
Upvotes: 3
Views: 4411
Reputation: 1501886
As I've said in my comments, it seems completely pointless to me, but you can easily just use reflection:
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);
}
}
Upvotes: 6