问题描述
我正在研究从数据库中获取数据并构建 protobuff 消息的东西.鉴于可以从数据库中获取某些字段的空值的可能性,我将在尝试构造 protobuff 消息时获得空指针异常.从线程 http://code.google.com/p/protobuf/issues/detail?id=57,我想知道处理 NPE 抛出的唯一其他方法是否是将手动检查插入到与 proto 对应的 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:
- 您可以编写一个代码生成器plugin 将
setOrClearFoo()
方法添加到每个 Java 类中.Java 代码生成器为此提供了插入点(请参阅该页面的末尾). - 您可以使用 Java 反射来迭代
p
的get*()
方法,调用每个方法,检查null
,然后如果非空,则调用builder
的set*()
方法.这将带来额外的好处,即您不必每次添加新字段时都更新复制代码,但它比编写显式复制每个字段的代码要慢得多.
- 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 ofp
, call each one, check fornull
, and then call theset*()
method ofbuilder
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 中的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!