How to programmatically enable assert?

2019-02-04 02:16发布

问题:

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;
    }
}

回答1:

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).



回答2:

Try

ClassLoader loader = getClass().getClassLoader();
setDefaultAssertionStatus(true);

or

ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);

EDIT:

based on the comments

    ClassLoader loader = ClassLoader.getSystemClassLoader();
    loader.setDefaultAssertionStatus(true);
    Class<?> c = loader.loadClass("MyClass");
    MyClass myObj = (MyClass) c.newInstance();


public class MyClass {

    private static final int foo[] = new int[]{4,5,67};
    MyClass()
    {
        assert foo.length == 10;
    }
}


回答3:

You can enable/disable assertions programmatically too:
http://download.oracle.com/docs/cd/E19683-01/806-7930/assert-5/index.html



回答4:

The simplest & best way can be:

public static void assertion(boolean condition, String conditionFailureMessage)
{
    if(!condition)
        throw new AssertionError(conditionFailureMessage);
}

No need to set -ea as VM argument .

call the function like :

assertion(sum>=n,"sum cannot be less than n");

If assertion fails, code will give AssertionError, else code will run safely.