Search code examples
javaconfigurationassertions

How to programmatically enable assert?


How can I programmatically enable assert for particular classes, instead of specifying command line param "-ea"?

public class TestAssert {

    private static final int foo[] = new int[]{4,5,67};


    public static void main(String []args) {
        assert foo.length == 10;
    }
}

Solution

  • This was a comment to @bala's good answer, but it got too long.

    If you just enable assertions then call your main class--your main class will be loaded before assertions are enabled so you will probably need a loader that doesn't reference anything else in your code directly. It can set the assertions on then load the rest of the code via reflection.

    If assertions aren't enabled when the class is loaded then they should be "Compiled Out" immediately so you are not going to be able to toggle them on and off. If you want to toggle them then you don't want assertions at all.

    Due to runtime compiling, something like this:

    public myAssertNotNull(Object o) {
        if(checkArguments) 
            if(o == null)
                throw new IllegalArgumentException("Assertion Failed");
    }
    

    Should work nearly as fast as assertions because if the code is executed a lot and checkArguments is false and doesn't change then the entire method call could be compiled out at runtime which will have the same basic effect as an assertion (This performance depends on the VM).