Force enabling of assertions

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

Example

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>(NuclearReactor.java:18)


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!
    if ( !hasAssertEnabled ) {
        throw new RuntimeException("Asserts must be enabled for NuclcearReactor.");
    }
  }

  /**
  * @param aName is non-null.
  */
  public NuclearReactor( final 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 //
  private final String fName;
}
 



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