使用 Java 中的注释使所有参数成为 final [英] Making all parameters final with an annotation in Java
问题描述
我最近一直在使用 Lombok——我想知道是否可以提供一个类级别或方法级别的注释,为所有参数添加 final.例如:
I've recently been working with Lombok--and I'm wondering it would be possible to provide a class level or method level annotation that adds final to all parameters. For example:
@finalizer
void foo(Bar bar);
成为
void foo(final Bar bar);
推荐答案
这是可能的.Lombok 可以做到,已经有了 FieldDefaults 注释,允许将所有字段设为 默认为 final
.对参数执行此操作会更容易.虽然字段上的 final
是 JVM 处理的事情(通过不允许赋值并在构造函数的末尾发出写屏障),但参数上的 final
只是一个编译时特性.
It is possible. Lombok could do it, there's already the FieldDefaults annotation allowing to make all fields final
by default. Doing this for parameters would be even easier. While final
on fields is something the JVM deals with (by not allowing assignments and issuing write barriers at the end of the constructor), final
on parameters is only a compile time feature.
这不可能.Lombok 目前没有这样做,作者的 opinion 是没有任何意义.
It isn't possible. Lombok doesn't do it currently and the author's opinion is that it makes no sense.
AFAIK 有强制执行 final
参数的工具.
AFAIK there are tools enforcing final
parameters.
如果在 Java 中一切都默认为 final
并且可以通过使用诸如 var
之类的东西来覆盖,我个人会非常高兴.但这个想法来得太晚了 20 年.
I'd personally be most happy if in Java everything was final
by default and could be overridden by using something like var
. But this idea is coming 20 year too late.
这篇关于使用 Java 中的注释使所有参数成为 final的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!