SFDC String.isEmpty vs. String.isBlank

SFDC String.isEmpty vs. String.isBlank

前言

项目接近尾声了,开始编写测试Class了。开始做测试类了之后发现了很多前期设计的问题,代码里考虑的不全面一下子全都显现出来了。
老生常谈的空NULL0(数字为零),''(空字符串),' '(只有空格)。
在字符串判断时候,发现String提供了两个类似的方法:
String.isEmpty(String str)
String.isBlank(String str)
这两个方法都返回一个Boolean

测试

Talk is cheap。show me the code!
写了点测试的代码,测测这俩方法有啥不同。

String strBlank = '';
String strNull = null;
String strSpace = ' ';

System.debug('isEmpty(strBlank):'+String.isEmpty(strBlank));
System.debug('isEmpty(strNull):'+String.isEmpty(strNull));
System.debug('isEmpty(strSpace):'+String.isEmpty(strSpace));
System.debug('============================================');
System.debug('isBlank(strBlank):'+String.isBlank(strBlank));
System.debug('isBlank(strNull):'+String.isBlank(strNull));
System.debug('isBlank(strSpace):'+String.isBlank(strSpace));

结果如图:

结论

可以通过Log得出结论

  1. 两个方法都对字符串为:NULL''(空字符串)都能Check出来
  2. String.isEmpty(strSpace) :会认为空格也是字符
  3. String.isBlank(String str):则更加严格一点,空格不被认为有效字符
原文地址:https://www.cnblogs.com/paynev/p/14919749.html