How to programmatically enable assert?

前端 未结 5 794
梦毁少年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:19

    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.

提交回复
热议问题