Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable assert statement to execute?

Tags:

java

I've written the following code:

class Cl
{
    public static void main (String[] args) throws java.lang.Exception
    {
        assert true; //1
        Bar.foo();
    }

    static class Bar{
        public static void foo(){
            boolean enabled = false;
            assert enabled = true;
            System.out.println("Asserts " + 
               (enabled ? "enabled" : "disabled"));
        }
    }
}

DEMO

JLS 14.10 says:

An assert statement that is executed after its class has completed initialization is enabled if and only if the host system has determined that the top level class that lexically contains the assert statement enables assertions.

I thought I enabled assertion by assert true in Cl class, but it's still not working. How can I enable an assertion regarding to what JLS said?

like image 468
St.Antario Avatar asked Dec 01 '25 21:12

St.Antario


2 Answers

Add the -ea option to your java command line when you run your program

like image 118
mikea Avatar answered Dec 04 '25 09:12

mikea


Run Your program like this,

java -ea YourClass

-ea means enable assertion and after running like this your assertions will be executed during runtime otherwise it just jump the assert statements.

If you are using eclipse go to Run Configuration and write -ea in VM Arguments and Run.

If you are trying to enable assertion programmatically you can try this,

     boolean enabled = false;
     ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
     assert enabled = true;
     System.out.println("Asserts " + 
        (enabled ? "enabled" : "disabled"));
like image 27
akash Avatar answered Dec 04 '25 09:12

akash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!