Introduction to the assertion function in J2SE 1.4

Source: Internet
Author: User

 


Summary
J2SE 1.4 added the assertion function in JAVA. In the simplest case, a Boolean expression can be written to any row in the JAVA code. If the expression is true, add the assert keyword at the beginning of the line of code, the Code continues to be executed. Otherwise, an exception is thrown. To implement this function, the assert keyword, AssertionError class, and JAVA. lang. ClassLoader are added with several new methods. This article describes how to use the assert keyword, how to control the assertion function from the command line, how to control the assertion function within the code, and when to use the assertion function. The assert keyword is mentioned below, while assertion indicates the statement or determination function.

The assertion function provides a mechanism for checking the correctness in the Code. This check is usually used in the Development and debugging stages and can be closed after the software is deployed. This allows programmers to add debugging check statements in the code, and disable the function after the software is deployed to avoid the impact on the software speed and memory consumption. Basically, the assertion function is a new error check mechanism in JAVA, but this function can be disabled as needed.

In C and C ++, it is usually concluded that functional statements can be preprocessed without being compiled into the final Execution Code. Because JAVA does not have macro functions, therefore, in the previous java version, it was concluded that the function was not widely used. In JDK1.4, this situation was changed by adding the assert keyword.

The most important feature of this new feature is that the statements can be turned on or off at runtime, which means that these statements with the error check function do not need to be deleted from the source code after the development process ends.

The assertion syntax is very simple, but correct use can help us compile robust (ROBAST) Reliable code. In this article, we will not only learn how to write the assertion statement, but also discuss the situation under which the assertion statement should be used.

I. Basic assertion syntax knowledge

We can use the new JAVA keyword assert to write the final statement. A statement has two valid forms:

Assert expression1;
Assert expression1: expression2;

Expression1 is a Boolean expression to be judged. It must be ensured that its value must be true during program execution. expression2 is optional and used when expression1 is false, the constructor passed to the thrown exception AssertionError. Therefore, the type of expression2 must be the parameter type of the valid AssertionError constructor. The following is an example of several statements:

Assert 0 <value;
Assert ref! = Null;
Assert count = (oldCount + 1 );
Assert ref. m1 (parm );
The expression after the assert keyword must be of the boolean type. Otherwise, an error occurs during compilation.

The following is a complete example of using a statement (see the bold statement line ):

Public class aClass {
Public void aMethod (int value ){
Assert value> = 0;
System. out. println ("OK ");
}
Public static void main (String [] args ){
AClass foo = new aClass ();
System. out. print ("aClass. aMethod (1 ):");
Foo. aMethod (1 );
System. out. print ("aClass. aMethod (-1 ):");
Foo. aMethod (-1 );
}
}

This program uses the assert value> = 0; statement to determine whether the parameter in the input aMethod method is not less than 0. If a negative number is input, the AssertionError exception is triggered.

To be compatible with programs earlier than J2SE 1.4, the javac and java commands in JDK disable the assertion function by default, that is, assert cannot be used as a keyword, this ensures that if you use assert as the variable name or method name in a previously written Program, the program can still run without modification. However, you must note that these programs cannot be re-compiled using the javac of JDK1.4. They can only be compiled using JDK1.3 or earlier versions. To compile the small program we wrote earlier, we must first use a J2SE 1.4-compliant compiler, and also use several command line parameters to enable the assertion function of the compiler.

Use the following command to compile aClass. java:

Javac-source 1.4 aClass. java

If we use java aClass to run this program, we will find that the assertion statement is not actually executed. Like javac, the java command disables the assertion function by default, therefore, the assertion statement is ignored. How to enable the assertion statement will be discussed in the next section.

2. Use command lines to control the assertion Function

One of the most important features of the assertion statement is that it can be closed. The function of closing is that although this code still exists in the program, the JVM ignores its existence when running the program, if the execution speed of the Code is not affected by the existence of the assertion statement, we can enable the assertion statement to help us analyze and judge the code. By default, this feature is disabled. (Note: the command line parameters described in this section are for JDK provided by SUN. If JDK is used by other companies, it may not be the same .)
In JDK1.4, use the command line option-ea (abbreviated as-enableassertions) of the java command to enable it. The following two commands are equivalent:

Java-ea myPackage. myProgram
Java-enableassertions myPackage. myProgram

Similarly, we disable the assertion function through-da (abbreviated as-disableassertions:

Java-da myPackage. myProgram
Java-disableassertions myPackage. myProgram

The assertion function can also be enabled or disabled for a specific package or class. For a class, use the complete class name. For a package, the package name is followed by "...":

Java-ea: myPackage. myProgram
Java-da:... myPackage. myProgram

When multiple-ea-da parameters are used in a java command, the subsequent parameter settings will overwrite the previous parameter settings. For example, we can enable all the assertion functions by default, however, this function is disabled for specific packages:

Java-ea-da:... myPackage. myProgram

For unnamed packages (in the current directory) all belong to the default package, you can use the following command to control:

Java-ea:... myPackage. myProgram
Java-da:... myPackage. myProgram

For all system classes that come with the JVM installation, you can use-esa (-enablesystemassertions) and-dsa (-disablesystemassertions) to control the enabling and disabling of the assertion function. Table 1.1 lists all the usage of the assertion function parameters.

Table 1 command line parameters related to the assertion function of java commands in JDK1.4

Command Line Parameters
Instance
Description
-Ea
Java-ea
Enable assertion for all classes except the system class
-Da Java-da
Disable assertion of all classes except the system class
-Ea: Java-ea: AssertionClass
Enable assertion of the AssertionClass class
-Da: Java-da: AssertionClass
Disable assertion of the AssertionClass class
-Ea:
Java-ea: pkg0...
Enable assertion of pkg0 package
-Da:
Java-da: pkg0...
Disable assertion of pkg0 packets
-Esa Java-esa
Enable assertion in the system class
-Dsa Java-dsa
Disable assertion in the system class

At this point, the small program named aClass we wrote earlier can be run with any of the following commands:

Java-ea aClass
Java-ea: aClass
Java-ea:... aClass

The running result is as follows:
AClass. aMethod (1): OK
AClass. aMethod (-1): java. lang. AssertionError
At aClass. aMethod (aClass. java: 3)
At aClass. main (aClass. java: 12)
Exception in thread "main"

Iii. inheritance relationship between assertion command line parameters
The enabling and disabling of the assertion function can be controlled to every class. A command line can accommodate any number of-ea-da parameters. How do these parameters interact, basically, two principles are followed: specific settings take precedence over general settings, and subsequent settings take precedence over the previous settings. Let's look at the following example:

// Base. java
Package tmp;
Public class Base {
Public void m1 (boolean test ){
Assert test: "Assertion failed: test is" + test;
System. out. println ("OK ");
}
}
// Derived. java
//
Package tmp. sub;
Import tmp. Base;
Public class Derived extends Base {
Public void m2 (boolean test ){
Assert test: "Assertion failed: test is" + test;
System. out. println ("OK ");
}
Public static void printAssertionError (AssertionError AE ){
StackTraceElement [] stackTraceElements = AE. getStackTrace ();
StackTraceElement stackTraceElement = stackTraceElements [0];
System. err. println ("AssertionError ");
System. err. println ("class =" + stackTraceElement. getClassName ());
System. err. println ("method =" + stackTraceElement. getMethodName ());
System. err. println ("message =" + AE. getMessage ());
}
Public static void main (String [] args ){
Try {
Derived derived = new Derived ();
System. out. print ("derived. m1 (false ):");
Derived. m1 (false );
System. out. print ("derived. m2 (false ):");
Derived. m2 (false );
} Catch (AssertionError AE ){
PrintAssertionError (AE );
}
}
}

There is a method m1 and m2 for the Base class and the Derived class. Because Derived is a subclass of the Base class, it inherits both the method m1.

First, after the assertion function of all classes is enabled, run the program:
Java-ea tmp. sub. Derived

Derived. m1 (false): AssertionError
Class = tmp. Bas

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.