How to programmatically test if assertions are enabled?

隐身守侯 提交于 2019-12-01 02:37:13

I use this

boolean assertOn = false;
// *assigns* true if assertions are on.
assert assertOn = true; 

I am not sure this is the "official" way.

Joe

The Oracle Java Tutorial provides information about how to do it...

http://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html

An excerpt from the tutorial

7. Why not provide a construct to query the assert status of the containing class?

Such a construct would encourage people to inline complex assertion code, which we view as a bad thing. Further, it is straightforward to query the assert status atop the current API, if you feel you must:

boolean assertsEnabled = false;
assert assertsEnabled = true; // Intentional side-effect!!!
// Now assertsEnabled is set to the correct value
RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
boolean assertionsEnabled = mx.getInputArguments().contains("-ea");
package io.github.baijifeilong.tmp;

import io.vavr.control.Try;

/**
 * Created by BaiJiFeiLong@gmail.com at 2019-04-18 09:12
 */
public class TmpApp {

    public static void main(String[] args) {
        Try.run(() -> {
            assert false;
        }).onSuccess($ -> {
            throw new RuntimeException("Assertion is not enabled");
        });
    }
}

Maybe help someone.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!