处理protobuffers中的空值 [英] Handling null values in protobuffers

查看:281
本文介绍了处理protobuffers中的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究从数据库中获取数据并构造protobuff消息的东西。鉴于可以从数据库中为某些字段提取空值,我将在尝试构建protobuff消息时获得Null指针异常。通过线程 http://来支持protobuffs不支持null code.google.com/p/protobuf/issues/detail?id=57 ,我想知道处理NPE的唯一其他方法是将手动检查插入到与原型对应的java文件中,如下所示!

I am working on something which fetches data from database and constructs protobuff message. Given the possibility that null values can be fetched from the database for certain fields , I will get Null-pointer exception while trying to construct the protobuff message. Getting to know that null is not supported in protobuffs from the thread http://code.google.com/p/protobuf/issues/detail?id=57, I am wondering whether the only other way to handle NPE getting thrown is to insert manual checks into the java file corresponding to the proto like below!

message ProtoPerson{
    optional string firstName = 1;
    optional string lastName = 2;
    optional string address1 = 3;
}

ProtoPerson.Builder builder = ProtoPerson.Builder.newBuilder();
if (p.getFirstName() != null) builder.setFirstName(p.getFirstName());
if (p.getLastName() != null) builder.setLastName(p.getLastName());
if (p.getAddress1() != null) builder.setAddress1(p.getAddress1());
...

所以有人可以澄清是否还有其他可行的有效方法在protobuff构造期间处理空值??

So can someone please clarify whether there is any other possible efficient way to handle the null values during protobuff construction??

推荐答案

对此没有简单的解决方案。我建议只处理空检查。但如果你真的想摆脱它们,这里有几个想法:

There's no easy solution to this. I'd recommend just dealing with the null checks. But if you really want to get rid of them, here are a couple ideas:


  • 你可以写一个代码生成器插件,添加 setOrClearFoo ()每个Java类的方法。 Java代码生成器为此提供插入点(请参阅该页面的结尾)。

  • 您可以使用Java反射来迭代 get *() <$ c $的方法c> p ,调用每一个,检查 null ,然后调用 set *() 方法如果非null。这将具有额外的优势,即每次添加新字段时都不必更新复制代码,但它比编写明确复制每个字段的代码要慢得多。

  • You could write a code generator plugin which adds setOrClearFoo() methods to each Java class. The Java code generator provides insertion points for this (see the end of that page).
  • You could use Java reflection to iterate over the get*() methods of p, call each one, check for null, and then call the set*() method of builder if non-null. This will have the added advantage that you won't have to update your copy code every time you add a new field, but it will be much slower than writing code that copies each field explicitly.

这篇关于处理protobuffers中的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆