How to programmatically enable assert?

前端 未结 5 799
梦毁少年i
梦毁少年i 2020-12-29 03:40

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

public class TestAssert {

    private sta         


        
5条回答
  •  半阙折子戏
    2020-12-29 04:31

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

提交回复
热议问题