速度,检查字符串是否为空且不为空的最有效方法是什么 [英] Velocity, what's the most efficient way to check if a string is empty and not null
问题描述
我经常遇到字符串值不存在和/或为空的情况.这是测试这种情况的最佳方法吗?
I often have cases when a string value is absent and/or empty. Is this the best way to test this condition?
#if( $incentive.disclaimer && $!incentive.disclaimer != '' )
$incentive.disclaimer
#end
推荐答案
如果您只是希望 Velocity 显示值(如果存在),或者如果不存在则不显示,安静参考 本身就可以解决问题:
If you just want Velocity to display the value if there, or display nothing if absent, a quiet reference by itself will do the trick:
$!incentive.disclaimer
如果您想明确测试是否为空,StringUtils<来自 Apache Commons Lang 的/a> 可以提供帮助.首先将其添加到您的上下文中(参考 此处):
If you're wanting to explicitly test for empty, StringUtils from Apache Commons Lang can help. First add it to your Context (reference here):
context.put("StringUtils", StringUtils.class);
尽管如果您使用的是较旧版本的 Velocity,它可能不喜欢类引用,因此您可以改为添加一个实例:
Though if you're on an older version of Velocity, it may not like the class reference, so you can add an instance instead:
context.put("StringUtils", new StringUtils());
然后你可以调用它的isEmpty 方法来自您的 Velocity 模板:
Then you can call its isEmpty method from your Velocity template:
#if($StringUtils.isEmpty($incentive.disclaimer))
## logic here...
#end
如果您希望将空格视为空,还有 isBlank.
If you want whitespace treated as empty, there's also isBlank.
这篇关于速度,检查字符串是否为空且不为空的最有效方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!