Groovy 或 Java 中是否有任何类型的算术安全导航运算符?
以下代码行位于我的一个 if
语句中:
$("#dateOfTransaction_month").val() != "${loadInstance?.payment?.dateOfTransaction?.getAt(Calendar.MONTH) + 1}"
由于 Java 的日期/时间管理非常混乱,我必须编写 + 1
才能获得正确的月份。问题是有时payment 对象可能不存在,所以我基本上会说
null + 1 。这给了我错误
Cannot invoke method plus() on null object
。有没有什么简洁的方法(类似于 Groovy 的 安全导航运算符) 我可以在 if
语句中考虑 payment 对象为 null 的可能性,或者我是否被迫检查该值在
if
语句?
The following line of code is in one of my if
statements:
$("#dateOfTransaction_month").val() != "${loadInstance?.payment?.dateOfTransaction?.getAt(Calendar.MONTH) + 1}"
Since Java's date/time management is such a mess I have to write + 1
to get the correct month. The problem is that sometimes a payment
object might not exist, so I would basically be saying null + 1
. This gives me the error Cannot invoke method plus() on null object
. Is there any neat way (neat being something like Groovy's safe navigation operator) I can account for the possibility of a payment
object being null in the if
statement, or am I forced to check to see if the value is null before the if
statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在您链接的同一页面上,实际上就在上面,是 Elvis 运算符(某些可能为空值?:默认值)。
使用 Elvis,您可以指定要使用的默认值。
例如
,默认为一月
On that same page you have linked, actually right above, is the Elvis operator (some-maybe-null-value ?: default).
With the Elvis you can assign a default value you want to use.
e.g.
Which would then default to being January
要解决使用烦人的 Java 日期和日历 API 的问题,您可以查看 JodaTime。与内置 API 相比,这是一个梦想。
To solve the issue of working with the annoying Java Date and Calendar API's you might check out JodaTime. It's a dream to work with when compared to the built in API's.
这是我在使用 Groovy 时真正喜欢它的一件事,即 ?。自动测试空引用的运算符。
Java 中没有这样的东西,您只需测试正在遍历的任何对象层次结构以检查空值:
但是,您的示例总是会引起麻烦,因为 Groovy 的 ?。当遇到 null 引用并返回 null 时,运算符只是停止遍历。
That is one thing i really like about Groovy when I played around with it, the ?. operator that automatically tested for null references.
There is no such thing in Java, you just have test whatever object hierarchy your are traversing to check for null values:
However, your example is always going to cause trouble, because Groovy's ?. operator simply stops your traversal when it encounters a null reference and returns null.
Groovy 向 Date 添加了一个 plus() 方法,这就是 + 运算符所调用的方法。您可以自己直接调用它并将安全导航操作符链接到它。
http://groovy.codehaus.org/groovy-jdk /java/util/Date.html#plus(int)
Groovy adds a plus() method to Date which is what the + operator calls. You can directly call this yourself and chain a safe-navigation operator to it.
http://groovy.codehaus.org/groovy-jdk/java/util/Date.html#plus(int)