protobuf java 自动反射_如何使用Java反射创建Protobuf实例?

通常,您将创建一个protobuf类实例,如下所示:

Bar.Builder bld = Bar.newBuilder();

bld.setXYZ(...

我有一个用Java反射实例化protobuf类的用例:

Class clsBar = Class.forName("com.xyz.Foo$Bar");

Object instance = clsBar.newInstance(); // error here!

Method mth = clsBar.getMethod(...);

上面的代码与普通的Java类一起正常工作.但是对于生成的protobuf类“ com.xyz.Foo $Bar”,它给我一个NoSuchMethodException,因为那里没有默认的公共构造函数.

关于如何使用Java Refection创建protobuf实例的任何建议?问题是针对真正擅长protobuf内部的人.谢谢!

解决方法:

我认为您应该全面学习:通过Builder类:

//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();

尽管我不确定在这种情况下反射有什么用,但这可能需要更深入地了解您要解决的确切问题.

标签:reflection,inner-classes,protocol-buffers,java

来源: https://codeday.me/bug/20191118/2027071.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值