Java Reflection - Class.desiredAssertionStatus() Examples

Code Snippets Java Reflection Java 


Class:

java.lang.Class

java.lang.Objectjava.lang.Objectjava.lang.Classjava.lang.Classjava.io.SerializableSerializablejava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.TypeTypejava.lang.reflect.AnnotatedElementAnnotatedElementLogicBig

Method:

public boolean desiredAssertionStatus()

Returns the assertion status of this class.

A newly created class's default assertion status is false (disabled).

The assertion status of a class can be changed at any time by invoking following method in class ClassLoader:

public void setClassAssertionStatus(String className, boolean enabled)

Above method has no effect if the named class has already been initialized.


Examples


package com.logicbig.example;

public class TestClass {
}

package com.logicbig.example;

public class MainClass {
public static void main(String[] args) {
System.out.println("Default Assertion status of TestClass: " +
TestClass.class.desiredAssertionStatus());

MainClass.class
.getClassLoader()
.setClassAssertionStatus("com.logicbig.example.TestClass", true);

TestClass b = new TestClass();
System.out.println("Assertion status of TestClass: " + TestClass.class.desiredAssertionStatus());
}
}

Output

Default Assertion status of TestClass: false
Assertion status of TestClass: true




package com.logicbig.example;

public class TestClass {
void doSomething() {
assert false;
}
}

package com.logicbig.example;

public class MainClass {
public static void main(String[] args) {
MainClass.class
.getClassLoader()
.setClassAssertionStatus("com.logicbig.example.TestClass", true);
TestClass b = new TestClass();
b.doSomething();
}
}

Output

Caused by: java.lang.AssertionError
at com.logicbig.example.TestClass.doSomething(TestClass.java:9)
at com.logicbig.example.MainClass.main(MainClass.java:13)
... 6 more




See Also