我有一个setter方法.
然后当运行另一个(比如生成)方法时,我需要检查我的字段的值.所以在String属性的情况下,我需要知道它是否包含值或者是否未设置.所以它可能是null,""或有意义的东西,有3种可能性.首先检查空值是否相当无聊:
if (s != null)
Run Code Online (Sandbox Code Playgroud)
然后换一个空字符串
if (!s.isEmpty())
Run Code Online (Sandbox Code Playgroud)
这里有一步检查吗?你可以告诉我,我可以使用空String初始化我的String字段.[这是常见的吗?]但是如果有人将null值传递给setter方法setS呢?那么在对该对象做某事之前,我们总是要检查Object值是否为null?
好吧,是的,setter方法可以检查它的值,如果字段为null,getter方法也可以返回非null值.但它是唯一的解决方案吗?对于程序员来说,在getter和setter中做太多工作了!
Joe*_*oel 14
Commons库,StringUtils.isBlank()或StringUtils.isEmtpy().
isEmpty相当于
s == null || s.length() == 0
Run Code Online (Sandbox Code Playgroud)
isBlank相当于
s == null || s.trim().length() == 0
Run Code Online (Sandbox Code Playgroud)
if(s != null && !s.isEmpty()){
// this will work even if 's' is NULL
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28133 次 |
最近记录: |