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?
Add the -ea option to your java command line when you run your program
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With