Protobuf 动态反射填充机制(JAVA)

利用此方案可进行自动化Protobuf的功能拓展,核心代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
com.google.protobuf.GeneratedMessage.Builder builder;
Object object;

/* 遍历protobuf builder体 取出字段 */
for (int i = 0; i < builder.getDescriptorForType().getFields().size(); i++) {

    FieldDescriptor pf = builder.getDescriptorForType().getFields().get(i);// 获取proto字段
    Field f = object.getClass().getDeclaredField(pf.getName());// 获取同名成员变量
    Method m = object.getClass().getMethod("get" + f.getName());// 获取该成员变量的get方法
    Object value = m.invoke(object);
    builder.setField(pf, value);

}

builder.build();

明者自明,不做过多解释了,本篇到此,谢谢关注。

BeiTown
2014-10-23

本文链接:Protobuf 动态反射填充机制(JAVA)

转载声明:BeiTown原创,转载请注明来源:BeiTown's Coder 编码之源,谢谢


Tags: ,

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>