我试图将两个不同的字符串分配给两个不同的变量,这两个变量依赖于 Ant 中的两个 bool 值。
伪代码(ish):
if(condition)
if(property1 == null)
property2 = string1;
property3 = string2;
else
property2 = string2;
property3 = string1;
我尝试过的是;
<if>
<and>
<not><isset property="property1"/></not>
<istrue value="${condition}" />
</and>
<then>
<property name="property2" value="string1" />
<property name="property3" value="string2" />
</then>
<else>
<property name="property2" value="string2" />
<property name="property3" value="string1" />
</else>
</if>
但是我收到包含“<if>
”的行的空指针异常。我可以使用 <condition property=...>
让它工作标签,但一次只能设置一个属性。我尝试使用 <propertyset>
但这也是不允许的。
我是 ant 新手,您可能已经猜到了:)。
加夫
最佳答案
有多种方法可以做到这一点。最简单的方法是仅使用两个 condition
语句,并利用属性不变性:
<condition property="property2" value="string1">
<isset property="property1"/>
</condition>
<condition property="property3" value="string2">
<isset property="property1"/>
</condition>
<!-- Properties in ant are immutable, so the following assignments will only
take place if property1 is *not* set. -->
<property name="property2" value="string2"/>
<property name="property3" value="string1"/>
这有点麻烦,而且扩展性不好,但对于只有两个属性,我可能会使用这种方法。
更好的方法是使用条件目标:
<target name="setProps" if="property1">
<property name="property2" value="string1"/>
<property name="property3" value="string2"/>
</target>
<target name="init" depends="setProps">
<!-- Properties in ant are immutable, so the following assignments will only
take place if property1 is *not* set. -->
<property name="property2" value="string2"/>
<property name="property3" value="string1"/>
<!-- Other init code -->
</target>
我们在这里再次利用属性不变性。如果您不想这样做,可以使用 unless
属性和额外的间接级别:
<target name="-set-props-if-set" if="property1">
<property name="property2" value="string1"/>
<property name="property3" value="string2"/>
</target>
<target name="-set-props-if-not-set" unless="property1">
<property name="property2" value="string2"/>
<property name="property3" value="string1"/>
</target>
<target name="setProps" depends="-set-props-if-set, -set-props-if-not-set"/>
<target name="init" depends="setProps">
<!-- Other init code -->
</target>
需要注意的是,target
的 if
和 unless
属性仅检查属性是否已设置,而不检查属性的值属性。
关于Ant (1.6.5) - 如何在一个 <condition> 或 <if> 中设置两个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1618493/