Question

I would like to do conditional compilation in a program of mine. I know that if you declare a public static final boolean the compiler will ignore the branch that is not traversed. Is it possible to have an ant target change a variable before building the program?

For example if I have:

final public static boolean windows = false;

I would like two ant targets: Windows and Mac. I would like the command ant windows to change the boolean to true, while ant mac leaves the variable as is.

Thanks.

Was it helpful?

Solution

You can get Ant to modify a properties file, and then you can read this file in your application pretty easily:
new Properties(new FileInputStream("filename" / new File(filename))),

and read properties using:
Boolean isWindows = new Boolean(properties.getProperty("windows"))

or:
String os = properties.getProperty("os").

You can use the Ant PropertyFile task for doing this: http://ant.apache.org/manual/Tasks/propertyfile.html.

Edit: here's an alternative using another task if you absolutely must edit the source code file using Ant:

<replaceregexp file="blah.java" match="public static final boolean WINDOWS = \"(.*)\"" replace="public static final boolean WINDOWS = \"" + ${properties.windows} + "\"" />
-- replace the code as your own as required. See http://ant.apache.org/manual/Tasks/replaceregexp.html for details.

OTHER TIPS

Skip ant and property files etc, Java already does this!

Use something like System.getProperty("os.name");

You should read the other answers carefully and see if there is a better solution for you. However, Ant does have a task to replace text in files. For example:

<replace file="${src}/MyFile.java" token="boolean windows=true" value="boolean windows=false"/>

The properties and the replace tasks should get you what you need. I concur that finding a different approach is a good idea.

However if for some reason the built in tasks will not get you what you need, it is pretty easy to write a custom task for ant. See http://ant.apache.org/manual/develop.html

You can also provide command-lind value as an argument while calling Java-main program from Ant.

For eg. ant -f build.xml "YouranttaskName" -Doperatingsys="windows"

Inside build.xml

<target name="YouranttaskName">
<java classname="javaclassname" fork="true" >
<arg value="${operatingsys}" />
</java>
</target> 

Inside java -main method this argument-value will be available in same order .i.e. args[0] contains "Windows".

You can write your logic by considering that what is your default OS value, as user may not provide commandline argument and then set 'boolean flag' parameter accordingly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top