Skip to content

Guice should refuse to inject final fields #245

Closed

Description

@gissuebot

From limpbizkit on September 11, 2008 02:41:36

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: http://code.google.com/p/google-guice/issues/detail?id=245

Activity

  1. gissuebot commented on Jul 7, 2014

    @gissuebot
    Author

    From robbie.vanbrabant on September 11, 2008 01:58:17

    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: https://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.

  2. gissuebot commented on Jul 7, 2014

    @gissuebot
    Author

    From limpbizkit on September 11, 2008 09:42:46

    Hmm... we probably won't be able to change this behaviour for backwards-compatibility reasons. Shucks.

    Labels: -Priority-Medium Priority-Low

  3. gissuebot commented on Jul 7, 2014

    @gissuebot
    Author

    From gili.tzabari on September 23, 2008 20:20:33

    Doesn't 2.0 give you the wiggle room to make these kinds of breaks?

  4. gissuebot commented on Jul 7, 2014

    @gissuebot
    Author

    From limpbizkit on November 14, 2008 15:09:09

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

    Status: WontFix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      ⌂ 换网址