Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create protobuf instances using java reflection?

Normally you create an protobuf class instance like this:

Bar.Builder bld = Bar.newBuilder();
bld.setXYZ(...

I have a usecase that uses the Java reflection to instantiate a protobuf class:

Class clsBar = Class.forName("com.xyz.Foo$Bar");
Object instance = clsBar.newInstance(); // error here!
Method mth = clsBar.getMethod(...);

The above code works fine with normal Java classes. But for a generated protobuf class "com.xyz.Foo$Bar", It gives me an NoSuchMethodException, as there isn't a default public constructor there.

Any suggestions on how to use Java refection to create protobuf instances? The question is for someone who's really good at protobuf internals. Thank!

like image 353
Nathan W Avatar asked Oct 20 '25 11:10

Nathan W


1 Answers

I think you should go the full way: through the Builder class:

//get Bar class
Class barClass = Class.forName("com.xyz.Foo$Bar");

//instantiate Builder through newBuilder method
Method newBuilderMethod = barClass.getMethod("newBuilder");
Bar.Builder builder = (Bar.Builder) newBuilderMethod.invoke(null);

// ... set properties  -- can be through reflection if necessary

//build:
Bar bar = builder.build();

Though I don't exactly see how reflection is of any use in this case, that would probably require a deeper understanding of the exact problem you are trying to solve.

like image 180
ppeterka Avatar answered Oct 23 '25 02:10

ppeterka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!