google-code-export / google-guice

Automatically exported from code.google.com/p/google-guice
Apache License 2.0
2 stars 1 forks source link

Guice should refuse to inject final fields #245

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Setting final fields directly using reflection has unpredictable results and 
shouldn't be supported.

From the Field.set() Javadoc:
  If the underlying field is final, the method throws an IllegalAccessException unless 
setAccessible(true) has succeeded for this field and this field is non-static. 
Setting a final field in 
this way is meaningful only during deserialization or reconstruction of 
instances of classes with 
blank final fields, before they are made available for access by other parts of 
a program. 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.

I believe we still need setAccessible(true) so we can update modify private 
non-final fields.

Original issue reported on code.google.com by limpbizkit on 11 Sep 2008 at 6:41

GoogleCodeExporter commented 9 years ago
As Bob once pointed out on the mailing list, it could make sense to @Inject 
private 
finals (e.g. into providers) because you get the same thread safety/visibility 
guarantees as you get with constructors: 
http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-3.html

I have currently used this in Warp Persist, here: http://code.google.com/p/warp-
persist/source/browse/trunk/warp-
persist/src/com/wideplay/warp/hibernate/SessionFactoryProvider.java

We can't let Guice create the object, but still want to use a final field. It 
seemed 
like the only way to do that. 

Now, Guice 2.0's getProvider will probably get rid of this use case, so in that 
case 
I'm not against removing support for this, because it sure does feel hacky.

Original comment by robbie.v...@gmail.com on 11 Sep 2008 at 8:58

GoogleCodeExporter commented 9 years ago
Hmm... we probably won't be able to change this behaviour for 
backwards-compatibility reasons. Shucks.

Original comment by limpbizkit on 11 Sep 2008 at 4:42

GoogleCodeExporter commented 9 years ago
Doesn't 2.0 give you the wiggle room to make these kinds of breaks?

Original comment by gili.tza...@gmail.com on 24 Sep 2008 at 3:20

GoogleCodeExporter commented 9 years ago
I'll reopen this if a problem comes up, but so far we haven't seen any bad 
behaviour
from this.

Original comment by limpbizkit on 14 Nov 2008 at 11:09