tags:

views:

56

answers:

2

Sorry if the question title is confusing. Let me explain further.

I am building a Java project with Eclipse. In my Java product I have conditionals that determine what code is included in the product and relies on static final constants for dead stripping.

class BuildFlags
{
    public static final boolean SOME_FLAG = true; // Need to set this programmatically
}

class SomeOtherClass
{
    public void someMethod()
    {
        if (BuildFlags.SOME_FLAG)
        {
            // flag specific code
        }
    }
}

My question is how can I change BuildFlags.SOME_FLAG (above) so that I can run a special build without changing the source? Is there some way I can pass flags to the jvm (from eclipse) which I can then access to set this flag programatically?

+3  A: 

You do this by setting a system property value (see the docs on java) and then getting it from System.getProperty(). System properties can be set in Eclipse by editing the run configuration.

Note that properties are set as strings -- you will have to convert it to a boolean.

Kathy Van Stone
Consider taking your properties from a property file, instead of from the command line. In this way, you can store groups of settings that belong together. Besides, you don't have to remember settings, since they are stored in a file.
Eric Eijkelenboom
If the 'dead code stripping' property of the static final flag is a requirement, I don't think this will work...
Kevin K
@Kevin You can't have a compiler optimization work with dynamically changing conditions, so no solution would work
Kathy Van Stone
@Kathy I understand, I'm just wondering if there's any way to configure the 'special build' to use dynamic conditions while still building the 'main build' with the static conditions.
Kevin K
@Kathy The condition isn't changing dynamically. It is constant (or needs to be) for the duration of the vm process.
Maven
@Maven It is dynamic relative to compilations, as I understood the problem; that is, a single set of .class files need to handle both cases. Or at least that was the problem I was giving a solution to.
Kathy Van Stone
@Kevin I could certainly write ant script code that could generate the appropriate BuildFlags.java file and then use that to run a compilation. It would even be rather simple as Ant can handle token substitution
Kathy Van Stone
@Kathy The preprocessor ala ant task seems like a logical solution. Of course this somewhat changes the issue in that the set of .class files will only handle one case. Thinking about it that is really what I want for these flags. Thanks.
Maven
A: 
java -DsomeFlag=true <class>

and

String flag = System.getProperty("someFlag");
Dean J