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
public class Main {
public static void main(String[] args) {
assert args.length > 0;
}
}
Assertions
public class MainClass {
public static void main(String[] arg) {
int a = 0;
assert a == 0;
}
}
java -enableassertions MyProg You can also use its abbreviated form -ea: java -ea MyProg
Assert with an informative message
public class MainClass {
public static void main(String[] args) {
assert false: "Here"s a message saying what happened";
}
}
Catch assert exception with message
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);
}
}
}
Compile "assert"
// 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;
}
}
Enabling Assertions from the Command Line: -ea and -da enable and disable assertion in a package subtree or in a class.
java -ea MyApp
java -ea:... MyApp
java -ea:com.mycompany... MyApp
java -ea:com.mycompany... -da:com.mycompany.MyClass MyApp
Handling an Assertion Error
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);
}
}
}
More Complex Assertions
assert logical_expression : string_expression;
public class MainClass {
public static void main(String[] arg) {
int value = 80;
assert false : "value: " + value;
}
}
Using the class loader to enable assertions
// 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()";
}
}