【发布时间】:2011-05-23 03:50:51
【问题描述】:
如何根据布尔属性可能具有的所有三种状态分叉三种不同的情况? Java 代码看起来很简单:
public class Foo {
public Boolean getBool() { return null /* this would be dynamic in RL */; }
}
// somewhere in the servlet code:
if (foo.getBool() == null) {
resp.getWriter().print("not yet set");
} else if (foo.getBool()) {
resp.getWriter().print("set to TRUE");
} else {
resp.getWriter().print("set to FALSE");
}
Velocity 似乎在这里失败了,因为规范没有 null 文字,并且为了简单起见,布尔/非 null 相等检查在某种程度上是可替代的。当然,有两种解决方案可以避免这种困境(见下文),但有没有一些直接/更清洁的方法?
-
只需向 Foo 类添加一个额外的 getter,如下所示:
boolean isBoolSet() {return getBool() != null; }
然后 VTL 代码将是:
#if(!$foo.boolSet)
not yet set
#else
#if($foo.bool)
set to TRUE
#else
set to FALSE
#end
#end
-
获取一些空值,像这样,
Object getTheNull() {return null; }
然后 VTL 看起来像:
#if($foo.bool == $foo.theNull)
not yet set
#else
#if($foo.bool)
set to TRUE
#else
set to FALSE
#end
#end
【问题讨论】:
-
嗯,我认为它的速度效率会降低,但最终使用枚举类型会更安全、更清洁......
-
这样会降低效率吗?几乎可以肯定效率更高。
-
好吧,我知道在 Android 等平台上不建议使用枚举类型,因为它比直接数值选项慢。我不确定两者在普通 java 环境中的速度差异,但可能是相似的,即使差异最终没有那么大。
标签: java velocity template-engine vtl