在 Guice 中使用最终字段进行字段注入

Field Injection with final field in Guice

the official document中可以看到这句话是关于字段注入的

Avoid using field injection with final fields, which has weak semantics.

为什么带final修饰符的字段注入没有意义? 谁能解释一下?

您实际上是在问以下问题:"weak semantics" 是什么意思?

一般来说,正如您所注意到的,"semantics" 是 "meaning"。此外,在编程中 semantics 指的是:

the rigorous...study of the meaning of programming languages.

当我们说"injecting final fields has weak semantics"时,意思是"injecting final fields makes it difficult to reason rigorously about the meaning of your program."

为什么?正如 Boris the Spider 在评论中指出的那样,"weak semantics" 指的是 this behaviour:

Use [of setting a final field using reflection] in any other context [than serialization] may have unpredictable effects, including cases in which other parts of a program continue to use the original value of this field"

这意味着如果你使用反射来设置一个final字段,你的程序的意义(语义)就会变得模糊,因为它现在具有不可预测的行为。

不可预知的行为正是链接文档中提到的:程序的其他部分可以继续使用 final 字段的原始值。不清楚程序的哪些部分正在使用原始值,哪些部分正在使用重新分配的值。