我该如何以编程方式启用特定类的断言,而不是指定命令行参数“-ea”?
public class TestAssert {
private static final int foo[] = new int[]{4,5,67};
public static void main(String []args) {
assert foo.length == 10;
}
}
我该如何以编程方式启用特定类的断言,而不是指定命令行参数“-ea”?
public class TestAssert {
private static final int foo[] = new int[]{4,5,67};
public static void main(String []args) {
assert foo.length == 10;
}
}
尝试一下
ClassLoader loader = getClass().getClassLoader();
setDefaultAssertionStatus(true);
或。ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
编辑:
基于评论
ClassLoader loader = ClassLoader.getSystemClassLoader();
loader.setDefaultAssertionStatus(true);
Class<?> c = loader.loadClass("MyClass");
MyClass myObj = (MyClass) c.newInstance();
public class MyClass {
private static final int foo[] = new int[]{4,5,67};
MyClass()
{
assert foo.length == 10;
}
}
public myAssertNotNull(Object o) {
if(checkArguments)
if(o == null)
throw new IllegalArgumentException("Assertion Failed");
}
如果代码被频繁执行,并且checkArguments为false并且不会改变,那么该方法调用整个过程可能在运行时被编译掉,因此其速度几乎与断言相同(这种性能取决于虚拟机)。
setClassAssertionStatus
更灵活,因为它允许在执行的各个点上启用/禁用断言检查,即使在类初始化之后。assert
语句的任何类生成$assertionsDisabled
字段。public class A {
public static void main(String[] args) {
assert false;
System.out.println(Arrays.toString(A.class.getDeclaredFields()));
}
}
将所需的断言状态设置为仅涉及设置此字段(请注意反转的布尔值):
// 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);
}
WARNING: An illegal reflective access operation has occurred[...]
可以使用 --add-opens java.base/java.lang.reflect=ALL-UNNAMED
来抑制这些消息。 - Arno Unkrig最简单且最好的方法可能是:
public static void assertion(boolean condition, String conditionFailureMessage)
{
if(!condition)
throw new AssertionError(conditionFailureMessage);
}
assertion(sum>=n,"sum cannot be less than n");
assert x
可能会产生影响,也可能不会。这是您的建议所无法实现的。 - Kalle Richter