3

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);
4
  • Surely if you know that you need a foo.Bar at compile-time (your last line shows that twice), you can go the normal route of deserialization. Please give more details about what you're trying to do. Commented Apr 12, 2013 at 5:43
  • the howTo is a common function, I want it can also create other message object. like foo.Bar b = (foo.Bar) howTo(rawbyte, "foo.Bar"); foo.Boom bm = (foo.Boom) howTo(rawbyte, "foo.Boom"); Commented Apr 12, 2013 at 5:47
  • here is a C++ demo github.com/chenshuo/recipes/blob/master/protobuf/codec.h#L35 Commented Apr 12, 2013 at 5:49
  • How is there any benefit in using howTo over using: foo.Boom bm = foo.Boom.parseFrom(rawBytes)? If you were trying to then use this just as a generic message that would make more sense, but if you know at compile-time what type you need, it just seems pointless. Commented Apr 12, 2013 at 5:53

1 Answer 1

6

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.