用@Immutable注释不可变的Java类的优点是什么? [英] What is the advantage of annotating an immutable Java class with @Immutable?

查看:149
本文介绍了用@Immutable注释不可变的Java类的优点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有了不变性的概念,为什么将DTO变成不变是个好主意.

I get the concept of immutability, and why it is a good idea to make DTOs immutable.

我还注意到Java具有@Immutable批注,可用于批注不可变的类.

I also notice that Java has an @Immutable annotation that we can use to annotate immutable classes.

我的问题是:将Java类注释为@Immutable给我们带来了什么?是否有仅适用于以这种方式注释的类的库功能?

My question is: what does annotating a Java class as @Immutable give us? Are there any library features that only work on classes annotated in this way?

推荐答案

该注释记录了您的类是不可变的事实,并告诉该类的用户您已遵循

The annotation documents the fact that your class is immutable and tells the users of the class that you have followed the contract defined in the annotation javadoc. It is also frequent to simply include a comment directly in the javadoc: this is the approach chosen by the JDK, see for example the javadoc of LocalDate.

某些静态分析工具(例如FindBugs)也可以使用该批注并验证该类确实是不可变的.例如,如果您忘记将公共场所定为决赛,FindBugs将发出警告.

Some static analysis tools such as FindBugs can also use that annotation and verify that the class really is immutable. If you forgot to make a public field final for example, FindBugs will emit a warning.

这篇关于用@Immutable注释不可变的Java类的优点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆