Ant(1.6.5) - 如何在一个<condition>或<if>中设置两个属性

gav*_*gav 13 ant if-statement properties conditional-statements

我试图将两个不同的字符串分配给两个不同的变量,这取决于Ant中的两个布尔值.

伪代码(ish):

if(condition)
   if(property1 == null)
      property2 = string1;
      property3 = string2;
   else
      property2 = string2;
      property3 = string1;
Run Code Online (Sandbox Code Playgroud)

我试过的是;

<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>
Run Code Online (Sandbox Code Playgroud)

但是我得到包含" <if>" 的行的空指针异常.我可以使用<condition property=...>标签让它工作,但一次只能设置一个属性.我尝试过使用,<propertyset>但也不允许这样做.

我是蚂蚁的新手,你可能已经猜到了:).

GAV

Jas*_*Day 34

有几种方法可以做到这一点.最简单的是只使用两个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"/>
Run Code Online (Sandbox Code Playgroud)

这有点麻烦,不能很好地扩展,但对于两个属性,我可能会使用这种方法.

更好的方法是使用条件目标:

<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>
Run Code Online (Sandbox Code Playgroud)

我们再次利用这里的财产不变性.如果您不想这样做,可以使用该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>
Run Code Online (Sandbox Code Playgroud)

重要的是要注意,仅检查属性是否设置的属性ifunless属性target,而不是属性的值.