如何以编程方式启用断言? [英] How to programmatically enable assert?

查看:102
本文介绍了如何以编程方式启用断言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以编程方式为特定类启用断言,而不是指定命令行参数-ea?

How can I programmatically enable assert for particular classes, instead of specifying command line param "-ea"?

public class TestAssert {

    private static final int foo[] = new int[]{4,5,67};


    public static void main(String []args) {
        assert foo.length == 10;
    }
}


推荐答案

如果你只是启用断言,然后调用你的主类 - 你的主类将在断言之前加载启用,所以你可能需要一个加载器,不直接引用代码中的任何东西。它可以设置断言,然后通过反射加载代码的其余部分。

If you just enable assertions then call your main class--your main class will be loaded before assertions are enabled so you will probably need a loader that doesn't reference anything else in your code directly. It can set the assertions on then load the rest of the code via reflection.

如果在加载类时没有启用断言,那么它们应该立即编译出,因此您无法打开和关闭它们。

If assertions aren't enabled when the class is loaded then they should be "Compiled Out" immediately so you are not going to be able to toggle them on and off. If you want to toggle them then you don't want assertions at all.

由于运行时编译,这样的:

Due to runtime compiling, something like this:

public myAssertNotNull(Object o) {
    if(checkArguments) 
        if(o == null)
            throw new IllegalArgumentException("Assertion Failed");
}

应该几乎和断言一样快,因为如果代码执行得很多, checkArguments是false并且不会改变,那么整个方法调用可以在运行时编译出来,这将具有与断言相同的基本效果(此性能取决于VM)。

Should work nearly as fast as assertions because if the code is executed a lot and checkArguments is false and doesn't change then the entire method call could be compiled out at runtime which will have the same basic effect as an assertion (This performance depends on the VM).

这篇关于如何以编程方式启用断言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆