velocity:三态布尔属性检查

时间:2010-12-09 22:00:33

标签: java velocity template-engine vtl

如何根据布尔属性可能具有的所有三种状态来分叉三种不同的情况? 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文字和boolean / not-null相等检查在某种程度上是为了简单起见。当然,有两种解决方案可以避免这种困境(见下文),但有一些简单明了的方法吗?

  1. 只需在Foo类中添加一个额外的getter,就像这样:

    boolean isBoolSet(){return getBool()!= null; }

  2. 然后VTL代码为:

    #if(!$foo.boolSet)
      not yet set  
    #else
      #if($foo.bool)
        set to TRUE
      #else
        set to FALSE  
      #end
    #end
    
    1. 获取一些空值,如此,

      Object getTheNull(){return null; }

    2. 然后VTL看起来像:

      #if($foo.bool == $foo.theNull)
        not yet set  
      #else
        #if($foo.bool)
          set to TRUE
        #else
          set to FALSE  
        #end
      #end
      

4 个答案:

答案 0 :(得分:4)

如果您使用现代版本的Velocity,您可以使用$ null或$ anyReferenceThatHasNoValue。您还可以使用#elseif来简化操作:

#if($foo.bool == $null)
  not yet set  
#elseif($foo.bool)
    set to TRUE
#else
    set to FALSE
#end

但严重的是,无论如何,这都是黑客攻击。你应该使用枚举。

答案 1 :(得分:2)

任何时候我都试图在不合适的地方偷窃一些东西,我总是后悔不仅仅是在一开始就转向更合适的状态。

给自己一个枚举,然后你可以明确地说它是NOT_READY。明确是好的。评论的一些额外代码是很棒的。

另一个例子是 - 如果你想知道创建一个新类或在现有类中放入更多代码,你可能需要2或3个新类。

请继续做下去。

答案 2 :(得分:1)

!$foo.bool && $foo.bool != false

相当于

$foo.bool == $null (in Velocity 1.6 onwards)

我猜这只是关于深夜编码和有点陈旧/简约的Velocity用户指南......

答案 3 :(得分:0)

为什么不在构造函数中初始化布尔值?这样它永远不会为空

相关问题