Joe
Joe

Reputation: 7919

How to programmatically test if assertions are enabled?

One of the correct answers from OCP Java SE 6 Programmer Practice Exams is:

You can programmatically test wheather assertions have been enabled without throwing an AssertionError.

How can I do that?

Upvotes: 25

Views: 6588

Answers (8)

Hakan Serce
Hakan Serce

Reputation: 11256

I guess you should use Class.desiredAssertionStatus()

Upvotes: 32

destan
destan

Reputation: 4411

Official solution*:

enter image description here

Source: http://hg.openjdk.java.net/javadoc-next/api/nashorn/rev/fa79d912da1b#l1.38


* As official as it gets:

As mentioned by @Hurkan Dogan here there was a AssertsEnabled.assertsEnabled() api in nashorn package which is now deprecated. However, its implementation could be considered as the official solution.

Also note that this solution is also written in the official docs and mentioned by @Joe here

Upvotes: 0

Christopher Mindus
Christopher Mindus

Reputation: 1

boolean ea=false;
try { assert(false); }
catch(AssertionError e) { ea=true; }

Upvotes: -1

Hürkan Doğan
Hürkan Doğan

Reputation: 31

I'm using AssertsEnabled from jdk.nashorn.internal.

System.out.println(AssertsEnabled.assertsEnabled());
// "assertsEnabled()" returns boolean value

Maybe it helps someone.

Upvotes: 1

BaiJiFeiLong
BaiJiFeiLong

Reputation: 4605

package io.github.baijifeilong.tmp;

import io.vavr.control.Try;

/**
 * Created by [email protected] 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.

Upvotes: -1

cnmuc
cnmuc

Reputation: 6145

RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
boolean assertionsEnabled = mx.getInputArguments().contains("-ea");

Upvotes: 1

Joe
Joe

Reputation: 7919

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

Upvotes: 23

Peter Lawrey
Peter Lawrey

Reputation: 533492

I use this

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

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

Upvotes: 35

Related Questions