4

In the official document, you can see this sentence about field injection.

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

Why doesn't field injection with final modifier have meanings? Could anyone explain?

shmosel
  • 49,289
  • 6
  • 73
  • 138
Kazuya Tomita
  • 667
  • 14
  • 34
  • 1
    From the linked document: "_Use in any other context may have unpredictable effects, including cases in which other parts of a program continue to use the original value of this field_". Seems like a bad idea to me. – Boris the Spider Feb 12 '17 at 10:23
  • 2
    Related: http://stackoverflow.com/a/3301720/1553851. See **Caveats**. – shmosel Feb 12 '17 at 10:25
  • @BoristheSpider What of what you quoted is wrong? – Kazuya Tomita Feb 13 '17 at 05:42
  • @shmosel Where is the related point? I want to know the perspective of why this is meaningless in terms of Dependencies Injection. – Kazuya Tomita Feb 13 '17 at 05:43
  • It's not a unique problem to DI, it's a generic problem with reflectively setting a `final` field, which is what the DI framework would be forced to do. – shmosel Feb 13 '17 at 05:47
  • I checked the question, but I am still not clear because the question focuses `private static final` modifier while my question considers just `final`. Could you give me very very short abstract? – Kazuya Tomita Feb 13 '17 at 10:26
  • Thanks for the accept! – David Rawson Apr 04 '17 at 01:36

1 Answers1

5

You are essentially asking the following: what does "weak semantics" mean?

In general, as you have noted, "semantics" is "meaning". Furthermore, in programming semantics refers to:

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

When we say "injecting final fields has weak semantics" it means that "injecting final fields makes it difficult to reason rigorously about the meaning of your program."

Why? As noted in the comment by Boris the Spider, "weak semantics" refers to 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"

It means that if you use reflection to set a final field, the meaning (semantics) of your program becomes obscure because it now has unpredictable behaviour.

The unpredictable behaviour is just that mentioned in the linked docs: other parts of the program can continue to use the original value of the final field. It becomes unclear which parts of the program are using the original value and which parts are using the reassigned value.

David Rawson
  • 20,912
  • 7
  • 88
  • 124