Java Tutorial/Development/Assertions
Содержание
- 1 A Program with Assertions
- 2 Assertions
- 3 Assert with an informative message
- 4 Catch assert exception with message
- 5 Compile "assert"
- 6 Enabling Assertions from the Command Line: -ea and -da enable and disable assertion in a package subtree or in a class.
- 7 Handling an Assertion Error
- 8 More Complex Assertions
- 9 Using the class loader to enable assertions
A Program with Assertions
<source lang="java">
public class Main {
public static void main(String[] args) { assert args.length > 0; }
}</source>
Assertions
<source lang="java">
public class MainClass {
public static void main(String[] arg) { int a = 0; assert a == 0; }
}</source>
java -enableassertions MyProg You can also use its abbreviated form -ea: java -ea MyProg
Assert with an informative message
<source lang="java">
public class MainClass {
public static void main(String[] args) { assert false: "Here"s a message saying what happened"; }
}</source>
Catch assert exception with message
<source lang="java">
public class Main {
public static void main(String[] argv) throws Exception { try { assert argv.length > 0 : "my message"; } catch (AssertionError e) { String message = e.getMessage(); System.out.println(message); } }
}</source>
Compile "assert"
<source lang="java">
// Non-informative style of assert // Compile with: javac -source 1.4 Assert1.java // {JVMArgs: -ea} // Must run with -ea public class MainClass {
public static void main(String[] args) { assert false; }
}</source>
Enabling Assertions from the Command Line: -ea and -da enable and disable assertion in a package subtree or in a class.
<source lang="java">
java -ea MyApp java -ea:... MyApp java -ea:com.mycompany... MyApp java -ea:com.mycompany... -da:com.mycompany.MyClass MyApp</source>
Handling an Assertion Error
<source lang="java">
public class Main {
public static void main(String[] argv) throws Exception { try { assert argv.length > 0; } catch (AssertionError e) { String message = e.getMessage(); System.out.println(message); } }
}</source>
More Complex Assertions
assert logical_expression : string_expression;
<source lang="java">
public class MainClass {
public static void main(String[] arg) { int value = 80; assert false : "value: " + value; }
}</source>
Using the class loader to enable assertions
<source lang="java">
// Compile with: javac -source 1.4 LoaderAssertions.java public class MainClass {
public static void main(String[] args) { ClassLoader.getSystemClassLoader() .setDefaultAssertionStatus(true); new Loaded().go(); }
} class Loaded {
public void go() { assert false: "Loaded.go()"; }
}</source>