IDEA @Contract annotation

-----------------------------------

http://www.jetbrains.com/help/idea/contract-annotations.html

@Contract

The @Contract annotation is used for defining a contract that a method must meet. This lets the IDE find problems in methods which call methods that you have annotated. You can use this annotation not only for annotating your own code but also for other existing libraries.

The @Contract annotation has two attributes — value and pure. The value attribute contains clauses describing causal relationship between arguments and the returned value.

The pure attribute is intended for methods that do not change the state of their objects, but just return a new value. If its return value is not used, removing its invocation will not affect program state or change the semantics, unless the method call throws an exception (exception is not considered to be a side effect).

A method should not be marked as pure if it does not produce a side effect by itself, but it could be used to establish the happens-before relation between an event in another thread, so that changes performed in another thread might become visible in current thread after invocation of this method. On the other hand, some synchronized methods could be marked as pure, because the purpose of synchronization here is to keep the collection internal integrity rather than to wait for an event in another thread. "Invisible" side effects (such as logging) that do not affect important program semantics are allowed.

A contract is a set of clauses that describe an input and an output. They are separated with the -> symbol: "A -> B". This forms a contract meaning that when you provide A to a method, you will always get B. Clauses in a contract must be separated with the ; (semicolon) symbol. For example:

@Contract("_, null -> null")

The method returns null if its second argument is null.

@Contract("_, null -> null; _, !null -> !null")

The method returns null if its second argument is null, and not-null otherwise.

@Contract("true -> fail")

A typical assertFalse() method which throws an exception if true is passed to it.

@Contract("_ -> this")

The method always returns its qualifier (e.g. StringBuilder.append).

@Contract("null -> fail; _ -> param1")

The method throws an exception if the first argument is null, otherwise it returns the first argument (e.g. Objects.requireNonNull).

@Contract("!null, _ -> param1; null, !null -> param2; null, null -> fail")

The method returns the first non-null argument, or throws an exception if both arguments are null (e.g. Objects.requireNonNullElse in Java 9).

Define a contract

  1. Press Alt+Enter on a method, and select Add method contract or Edit method contract.

  2. Configure the contract and apply the changes.

Syntax

The @Contract annotation value has the following syntax:

contract ::= (clause ‘;’)* clause
clause ::= args ‘->’ effect
args ::= ((arg ‘,’)* arg )?
arg ::= value-constraint
value-constraint ::= ‘_’ | ‘null’ | ‘!null’ | ‘false’ | ‘true’
effect ::= ‘_’ | ‘null’ | ‘!null’ | ‘false’ | ‘true’ | ‘fail’ | ‘new’ | ‘this’ | ‘param’ number
number ::= [1-9] [0-9]*

The constraints are:

_

Any value

null

Null value

!null

Value statically proved not to be null

true

True boolean value

false

False boolean value

fail

The method throws an exception if arguments meet argument constraints

new

Every time the method is executed, it returns a non-null new object that is distinct from other objects existing in the heap prior to method execution. If the method is pure, the new object is not stored in any field or array and will be lost if method return value is not used.

this

The method returns non-null this reference

param1 (param2, param3, etc.)

The method returns its first (second, third, etc.) argument

 
  Last modified: 22 January 2019

----------------------------------

来源 https://blog.jetbrains.com/idea/2013/10/better-control-flow-analysis-with-contract-annotations-and-intellij-idea-13/

Better Control Flow Analysis with Contract Annotations and IntelliJ IDEA 13

As we’re closing in on the release date, we’re going to publish more details on the new features of IntelliJ IDEA 13. Today we’d like to tell you about the new @Contract annotation.

If you are aware of @Nullable/@NotNull annotations, you probably know how helpful they are against NullPointerException. The new @Contract annotation brings one more layer of safety for your code by defining dependencies between method arguments and return values. This information lets IntelliJ IDEA provide smarter control flow analysis for your code and avoid probable errors.

Here’s an example: say we’ve got a method sort() that returns a sorted list or a null value if the argument is null.

Now if we try to to call this method with a null value and check the result against null, IntelliJ IDEA will not complain because it doesn’t know that a null input yields a null output.

How can we help IntelliJ IDEA? That’s right… Decorate the sort() method with a @Contractannotation, specifying that null inputs yield null outputs:

Now IntelliJ IDEA can see that the sort() method always returns null and the if statement is redundant. The corresponding message appears in the editor.

The @Contract annotation value has the following syntax:

  • contract ::= (clause ‘;’)* clause
  • clause ::= args ‘->’ effect
  • args ::= ((arg ‘,’)* arg )?
  • arg ::= value-constraint
  • value-constraint ::= ‘any’ | ‘null’ | ‘!null’ | ‘false’ | ‘true’
  • effect ::= value-constraint | ‘fail’

The constraints denote the following:

  • _ – any value
  • null – null value
  • !null – a value statically proved to be not-null
  • true – true boolean value
  • false – false boolean value
  • fail – the method throws exception, if the arguments satisfy argument constraints

The @Contract annotation is a powerful and flexible tool that helps make your APIs safer. However, you can use it not only for annotating your own code but also for other existing libraries.

Once you’ve configured the annotations for the project libraries, the IDE stores this information in simple XML files so it can be shared with the team via version control.

To enable the annotations in your project, just add <IntelliJ IDEA Home>/lib/annotations.jar to the classpath via Project Structure.

UPDATE: Please find the latest annotations.jar in Maven repository.

Develop with Pleasure!

--------------------------

https://scratchpad101.com/2015/08/06/annotations-are-evil/

Are annotations bad?

We sacrifice the art of writing good and performant code for the short term gains of improving developer productivity.

Annotations can be powerful but only when used to add context and information to the code. But trying to configure your application with them is nothing less that a crime.

============= End

IDEA @Contract annotation的更多相关文章

  1. Android 注解的一些应用以及原理

    在这边文章之前你首先需要对java 的注解部分有一个基本的了解(不需要太过的深入). 简单来说,注解这个东西就是用于辅助我们开发java代码的,注解本身无法干扰java源代码的执行. 在android ...

  2. spring boot获取request

    1. Controller中 1.1 通过静态方法获取 HttpServletRequest request = ((ServletRequestAttributes)RequestContextHo ...

  3. Effective Java 08 Obey the general contract when overriding equals

    When it's the case that each instance of the class is equal to only itself. 1. Each instance of the ...

  4. 谈谈WCF中的Data Contract(3):WCF Data Contract对Collection & Dictionary的支持

    谈谈WCF中的Data Contract(3):WCF Data Contract对Collection & Dictionary的支持 在本篇文章上一部分Order Processing的例 ...

  5. 秒懂,Java 注解 (Annotation)你可以这样学 - CSDN博客

    https://blog.csdn.net/briblue/article/details/73824058 文章开头先引入一处图片. 这处图片引自老罗的博客.为了避免不必要的麻烦,首先声明我个人比较 ...

  6. Java 注解 (Annotation)你可以这样学

    注解语法 因为平常开发少见,相信有不少的人员会认为注解的地位不高.其实同 classs 和 interface 一样,注解也属于一种类型.它是在 Java SE 5.0 版本中开始引入的概念. 注解的 ...

  7. 【Java】-NO.17.EBook.4.Java.1.014-【疯狂Java讲义第3版 李刚】- Annotation

    1.0.0 Summary Tittle:[Java]-NO.17.EBook.4.Java.1.014-[疯狂Java讲义第3版 李刚]-  Annotation Style:EBook Serie ...

  8. 秒懂,Java 注解 (Annotation)你可以这样学

    转自: https://blog.csdn.net/briblue/article/details/73824058 文章开头先引入一处图片. 这处图片引自老罗的博客.为了避免不必要的麻烦,首先声明我 ...

  9. Java 注解 (Annotation)

    Java 注解用于为 Java 代码提供元数据.作为元数据,注解不直接影响你的代码执行,但也有一些类型的注解实际上可以用于这一目的.Java 注解是从 Java5 开始添加到 Java 的. 注解语法 ...

随机推荐

  1. 小L记单词

    题目描述 小L最近在努力学习英语,但是对一些词组总是记不住,小L小把这些词组中每一个单词的首字母都记一下,这样形成词组的缩写,通过这种方式小L的学习效率明显提高. 输入 输入有多行,每组测试数据占一行 ...

  2. 网络七层模型及TCP、UDP,一次HTTP请求都发生了什么

    一.七层网络模型 http协议运行在应用层   二.TCP-UDP TCP.UDP协议的区别 一次Http 请求,这个过程都发生了什么 TCP 协议如何保证可靠传输 HTTP和HTTPS的区别 TCP ...

  3. [2017BUAA软工助教]团队建议

    关于团队项目的个人建议 (以下排名不分先后) 一.hotcode5 你们组要做一个"课件-心得"共享平台 目前最大的竞争对手其实不是北航课程中心网站,而是每个系自己的大班群. 热心 ...

  4. Liunx 简单的命令说明

    cd命令在linux中用来切换或者进入目录,路径还分为相对路径和绝对路径 cd 命令:切换当前目录至其他目录 cd /:加上斜杠表示是进入到根目录. pwd命令:查看当前路径. ()cd 进入用户主目 ...

  5. C#复习笔记(3)--C#2:解决C#1的问题(可空值类型)

    可空值类型 C#2推出可空类型来表示可以为null的值类型.这是一个呼声很高的需求,因为在常用的数据库中都是允许某些值类型可为空的.那么为什么值类型就不能为空呢?内存中用一个全0的值来表示null,但 ...

  6. if判断条件注意!!!

    if(condition){ console.log(condition为true才执行): } 实际上会对condition执行Boolean()转型函数,将其转换成布尔值

  7. Oracle RMAN备份与还原注意事项

    1 备份文件管理 如果要删除之前的备份,不要手动去目录下删除,应该在rman命令模式下使用删除命令,否则虽然在磁盘上把物理备份文件删除了,但是使用备份查看命令会一直看到已经删除的备份文件 list b ...

  8. Tomcat异常及解决办法——持续更新中

    公司项目,开发语言为java,中间件为Tomcat,运行过程中,从Tomcat出现了一些异常,现将异常及解决办法记录如下,仅供参考.(不断在补充中.......) 异常一: 1.日志内容 org.ap ...

  9. hdu1421_搬寝室

    题目:搬寝室 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1421 #include<stdio.h> #include<algor ...

  10. vue页面是否缓存的两种方式

    第一种 <keep-alive> <router-view v-if="$route.meta.keepAlive"></router-view> ...