一步检查空值和&字符串的空虚 [英] One step check for null value & emptiness of a string

查看:94
本文介绍了一步检查空值和&字符串的空虚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个setter方法。

I have a setter method.

然后当运行另一个(比如生成)方法时,我需要检查我的字段的值。
所以在String属性的情况下,我需要知道它是否包含值或者是否未设置。
因此它可能为null,或有意义的东西,有3种可能性。
首先检查空值是否相当无聊:

Then when another (say generate) method is run, I need to check the value of my fields. So in the case of String property, I need to know if it contains the value or if it was not set. So it may be null, "" or something meaningful, there are 3 possibilities. And it is rather boring to check first for a null value :

if (s != null)

然后是空字符串

if (!s.isEmpty())


这里有一步检查吗?你可以告诉我,我可以使用空String初始化我的String字段。 [这是常见的吗? ]但是如果有人将null值传递给setter方法setS呢?
所以我们总是要在对该对象做某事之前检查Object值是否为null?

嗯,是的,setter方法可以检查它的值,并且getter方法也可以返回非null值该字段为空。但它是唯一的解决方案吗?在getter& ;;这是太多的工作程序员要做的事情!

Well, yes a setter method can check it's values and also a getter method can return a non-null value if the field is null. But is it the only solution? It 's too much work in getters & setters for a programmer to do!

推荐答案

Commons library, StringUtils.isBlank() StringUtils.isEmtpy()

Commons library, StringUtils.isBlank() or StringUtils.isEmtpy().

isEmpty相当于

isEmpty is equivalent to

s == null || s.length() == 0

isBlank相当于

isBlank is equivalent to

s == null || s.trim().length() == 0

这篇关于一步检查空值和&字符串的空虚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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