Protobuf 动态反射填充机制(JAVA) 十月 23rd, 2014 79 views 利用此方案可进行自动化Protobuf的功能拓展,核心代码如下
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
Tags: Protobuf, 动态反射