Skip to content

Instantly share code, notes, and snippets.

@ThomasLau
Last active August 29, 2015 14:21
Show Gist options
  • Save ThomasLau/e629973e84be54cbbe5a to your computer and use it in GitHub Desktop.
Save ThomasLau/e629973e84be54cbbe5a to your computer and use it in GitHub Desktop.
Protobuf 动态反射填充机制

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, 动态反射

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment