How to programmatically enable assert?

落花浮王杯 提交于 2019-11-30 04:25:20

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

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

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

Rajarshee Mitra

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!