How to programmatically test if assertions are enabled?
Asked Answered
D

8

24

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?

Dripping answered 23/10, 2012 at 11:57 Comment(0)
M
34

I use this

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

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

Mehalick answered 23/10, 2012 at 12:3 Comment(5)
Every time true is false ;)Mehalick
And looking at @Joe's answer, apparently the "official" way, too.Chalky
They even call it "straightforward", so please delete your comment again, @PeterLawrey :DPrince
I am not sure this is the "official" way -- it's not. 2 beers fine for not knowing the core classes in Java (since 1.4) Class.desiredAssertionStatus()Borate
@Thilo, it's not the official way, it's a well defined API function in Class to do so.Borate
T
31

I guess you should use Class.desiredAssertionStatus()

Tarsuss answered 23/10, 2012 at 12:2 Comment(5)
This avoids the possible "accidental assignment" warning that comes with the other approach.Harlamert
Actually, from the javadoc: "Note that this method is not guaranteed to return the actual assertion status that was (or will be) associated with the specified class when it was (or will be) initialized.". So this answer seems incorrect to me, and you should consider Joe's answer.Facilitation
@FBB, I'm guessing it should be safe to invoke this method from inside an instance of the class you are testing against (because the class is guaranteed to be initialized).Battement
@Gili: "when it was (or will be) initialized". So, no, the javadoc states it is not safe, even if the class was correctly initialized.Facilitation
@Facilitation the other answer has exactly the same issue, it only checks whether assertions are enabled at the point the assertion is (or isn't) evaluated.Stoneblind
D
23

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
Dripping answered 23/10, 2012 at 12:25 Comment(0)
K
1
RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
boolean assertionsEnabled = mx.getInputArguments().contains("-ea");
Koblas answered 2/12, 2015 at 8:52 Comment(1)
Assertions can be enabled per-class and package, and can be changed by instrumentation.Stoneblind
S
1

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

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

Maybe it helps someone.

Seiler answered 1/6, 2020 at 16:47 Comment(0)
N
0

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

Nerland answered 28/11, 2022 at 11:6 Comment(0)
G
-1
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.

Gemology answered 20/9, 2019 at 3:45 Comment(1)
OP asked specifically for a solution "without throwing an AssertionError"Enculturation
P
-1
boolean ea=false;
try { assert(false); }
catch(AssertionError e) { ea=true; }
Perambulator answered 11/8, 2022 at 17:3 Comment(1)
OP asked specifically for a solution "without throwing an AssertionError"Enculturation

© 2022 - 2024 — McMap. All rights reserved.