How to programmatically enable assert?

Saideira picture Saideira · Apr 5, 2011 · Viewed 11.1k times · Source

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

Answer

Bala R picture Bala R · Apr 5, 2011

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