Force enabling of assertions

It's sometimes useful to require assertions to be always enabled for a particular class at runtime.


If NuclearReactor is loaded into an environment which has disabled assertions, then its static initializer will throw a RuntimeException.

Two example runs of NuclearReactor give :
>java -cp . -enableassertions NuclearReactor
Proceeding normally...
>java -cp . NuclearReactor
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.RuntimeException: Asserts must be enabled for NuclcearReactor.
        at NuclearReactor.<clinit>(

public final class NuclearReactor {

  public static void main(String... arguments){
    NuclearReactor reactor = new NuclearReactor("Fermi");
    System.out.println("Proceeding normally...");

  * Prevent this class from running with assertions disabled.
  * If assertions are disabled, then a RuntimeException will be
  * thrown upon class loading.
  static {
    boolean hasAssertEnabled = false;
    assert hasAssertEnabled = true; // rare - an intentional side effect!
      throw new RuntimeException("Asserts must be enabled for NuclearReactor.");

  * @param aName is non-null.
  public NuclearReactor(String aName){
    //do NOT use assert to verify parameters passed to
    //non-private methods
    if(aName == null){
      throw new IllegalArgumentException("Name cannot be null.");
    fName = aName;

  public String getName(){
    return fName;

  private final String fName;

Would you use this technique?
Yes   No   Undecided   
© 2015 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -