如何将两个属性与数值进行比较?

时间:2011-01-09 15:11:22

标签: ant

如何找出两个数字属性中哪一个最大?

以下是检查两者是否相等的方法:

<condition property="isEqual">
    <equals arg1="1" arg2="2"/>
</condition>

3 个答案:

答案 0 :(得分:8)

Ant script任务允许您使用脚本语言实现任务。如果安装了JDK 1.6,Ant可以执行JavaScript而无需任何其他依赖库。例如,此JavaScript读取Ant属性值,然后根据条件设置另一个Ant属性:

<property name="version" value="2"/>

<target name="init">
  <script language="javascript"><![CDATA[
    var version = parseInt(project.getProperty('version'));
    project.setProperty('isGreater', version > 1);
  ]]></script>

  <echo message="${isGreater}"/>
</target>

答案 1 :(得分:4)

不幸的是,内置condition task的Ant没有IsGreaterThan元素。但是,您可以使用IsGreaterThan condition项目中提供的Ant-Contrib。另一种选择是推出your own task以进行比较。我更喜欢前者,因为它更容易,更快,而且你还可以从useful tasks获得许多其他Ant-Contrib

答案 2 :(得分:2)

If you don't want to (or cannot) use the Ant-Contrib libraries, you can define a compare task using javascript:

<!-- returns the same results as Java's compareTo() method: -->
<!-- -1 if arg1 < arg2, 0 if arg1 = arg2, 1 if arg1 > arg2 -->
<scriptdef language="javascript" name="compare">
    <attribute name="arg1" />
    <attribute name="arg2" />
    <attribute name="result" />
    <![CDATA[
    var val1 = parseInt(attributes.get("arg1"));
    var val2 = parseInt(attributes.get("arg2"));
    var result = (val1 > val2 ? 1 : (val1 < val2 ? -1 : 0));
    project.setProperty(attributes.get("result"), result);
    ]]>
</scriptdef>

You can use it like this:

<property name="myproperty" value="20" />
...
<local name="compareResult" />
<compare arg1="${myproperty}" arg2="19" result="compareResult" />
<fail message="myproperty (${myproperty}) is greater than 19!">
    <condition>
        <equals arg1="${compareResult}" arg2="1" />
    </condition>
</fail>