How can I programmatically enable assert for particular classes, instead of specifying command line param \"-ea\"?
public class TestAssert {
private sta
It is possible to enable or disable assertions using reflection. As usual with reflection, the solution is fragile and may not be appropriate for all usage scenarios. However, if applicable and acceptable, it is more flexible than setClassAssertionStatus because it allows to enable/disable assertions checks at various points in the execution, even after the class is initialized.
This technique requires a compiler that generates a synthetic static field to indicate whether assertions are enabled or not. For example, both javac and the Eclipse compiler generate field $assertionsDisabled
for any class that contains an assert
statement.
This can be verified as follows:
public class A {
public static void main(String[] args) {
assert false;
System.out.println(Arrays.toString(A.class.getDeclaredFields()));
}
}
Setting the desired assertion status just comes down to setting this field (note the inverted boolean value):
// Helper method in any class
public static void setAssertionsEnabled(Class> clazz, boolean value)
throws ReflectiveOperationException
{
Field field = clazz.getDeclaredField("$assertionsDisabled");
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(Test.class, !value);
}