Home  >  Article  >  类库下载  >  Learning the java keyword assert

Learning the java keyword assert

高洛峰
高洛峰Original
2016-10-09 09:04:061773browse

When I was studying Java source code, I discovered the uncommon keyword assert. Let’s directly introduce the use of this keyword.

What is assert?

It is a newly added keyword after jdk1.4 and is gone.

What is the function of assert?

assert is used for assertions in many programming languages.

But what is an assertion?

Is it just a simple judgment of whether a Boolean expression is true?

Okay, with these questions, let’s get straight to the point.

assert vt vt. Maintain, persist; assert; advocate; claim.

By looking at the translation of assert, we can see that assert means assertion, maintenance and persistence.

In other words, the conditions following assert (anti-theft connection: this article was first published from http://www.cnblogs.com/jilodream/) must be met and must be maintained, otherwise an error will occur.

assert The use of

assert includes two parts

(1) The use of keywords in the code:

assert There are two ways to use it:

 1) assert BooleanCondition;

asssert followed by A Boolean expression.

If the value of the expression is true, then the current conditions are considered to meet the requirements and the business code continues to be executed.

If the value of the expression is false, then it is considered that the current condition does not meet the requirements and an AssertionError will be thrown immediately.

AssertionError extends Error extends Throwable.Throw is a class that is rarely used. It also has a subclass called Exception. Errors, like Exceptions, are serious problems that the system should not try to catch.

 2) assert BooleanCondition:Excepiton

assert is followed by a Boolean expression and an expression whose return value is a basic type.

When the expression is true, the remaining business code will continue to be executed (Anti-theft connection: this article was originally published from http://www.cnblogs.com/jilodream/), and the expression following ‘:’ will not be executed.

When the expression is false, the expression following ‘:’ will be executed, and the result will be placed in the AssertionError exception and thrown.

Here is a code example:

public class assertStudy
{
    public static void main(String args[]) 
    {
        assert 1 == 1;
        System.out.println("A Go!");
        System.out.println("\n-----------------------------------------------\n");
        assert 1 != 1 : "Wrong";
        System.out.println("B Go!");
    }
}

(2) Validity of keywords

Add a breakpoint at the above assert. When debugging, you find that there is no pause at the breakpoint, but it is skipped directly.

Why is this happening? This is because the assert keyword is configured by the java startup item.

At startup, you need to turn on the switch through -ea

java -ea assertStudy

In this way, we will see that the breakpoint in the assert line takes effect (it is not enabled by default).

And

java -da assertStudy, so assert will be invalid.

The method to enable keyword validity in eclipse is as follows:

Select menu: Run--->Run...--->Select the Arguments tab

Enter: -ea in the VM arguments text box. Note that there is no space in the middle. If you enter -da, it means that assertions are prohibited

(If you cannot find the above path, please open it in sequence (anti-theft connection: This article was first published from http://www .cnblogs.com/jilodream/ ) Start assertion: windows -> Preferences -> Java ->Installed JREs -> Click on the JDK being used -> Edit -> Default VM Arguments Enter in the text box: -ea)

The necessity of assert

Through the description of assert, we find that it is very similar to if in Java. So why does java add such a keyword? And should it be added in a subsequent version like jdk1.4?

Pay attention to the description of assert and the exception thrown is an Error.

The original intention of assert is to judge the condition that no problem will occur under normal use in the environment. These codes often appear in core codes such as base classes, framework classes, and tool classes. In the normal operation of these codes, there will be no parameter exceptions (anti-theft connection: this article was first published from http://www.cnblogs.com/jilodream/). However, once certain key values ​​are changed through reflection, dynamic proxy, etc., it will lead to a large number of abnormal scenarios. And if we add a large number of if judgments that are basically ineffective in order to protect these scenarios, then these if judgments that are basically ineffective will not only seriously affect the readability and simplicity of the code, but also make readers feel that these abnormalities Scenarios occur frequently and have a certain impact on system performance.

And assert can effectively control whether this code takes effect through configuration items. This is actually a very elegant behavior.

ps After writing this paragraph, I feel very much like a TV shopping....

Some other situations

1. -ea and -da can effectively point to a certain level of the class and package paths, This makes it possible to more flexibly control the effectiveness of assert. The specific usage is as follows:

-ea java -ea opens the assertion of all user classes

-da java -da closes the assertion of all user classes

-ea: java -ea:MyClass1 opens the assertion of MyClass1

-da: java -da: MyClass1 Close the assertion of MyClass1

-ea: java -ea:pkg1 Open the assertion of the pkg1 package -da: java

-da:pkg1 Close the assertion of the pkg1 package

-ea:... java -ea :... Open the assertion of the default package (unnamed package)

-da:... java -da:... Close the assertion of the default package (unnamed package)

-ea:... java -ea :pkg1... Open the assertion of the pkg1 package and its sub-packages

-da:... java -da:pkg1... Close the assertion of the pkg1 package and its sub-packages

-esa java -esa Open the assertion of the system class

-dsa java -dsa Close the assertion of the system class

2. The use of assert means that you know that this thing will never happen under normal circumstances, but you also know that things in the OS and jvm will occasionally have inexplicable errors, and at the same time, you are not allowed to call you. The person who wrote the code is different from what you thought and called your code incorrectly. So:

1) assert is often placed in the user's core processing code. If you look at the java source code, you will find that there are a lot of assert keywords in the source code.

2) assert handles situations that will never occur under normal circumstances, so assert is used in normal business processes.

3) Assert is not inheritable

If the assert of the parent class is turned on, when the assert method of the subclass is run, the subclass will not be turned on by default.

On the contrary, if you enable the assert of the subclass, when the assert method of the parent class is run, the assert of the parent class will not be enabled.

Reference documentation

http://blog.sina.com.cn/s/blog_95feae0d0101hhcg.html

http://lavasoft.blog.51cto.com/62575/43735

http://www. zhihu.com/question/24461924


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn