[concurrency-interest] Joda-Time immutability

Attila Szegedi szegedia at gmail.com
Mon Jun 20 12:52:19 EDT 2011


Well, to me it looks like it's implemented:

import java.lang.reflect.Field;

public class TestFinalField {
  public final int x = 1;

  public static void main(String[] args) throws Exception {
    TestFinalField tff = new TestFinalField();
    Field f = tff.getClass().getField("x");
    f.setAccessible(true);
    f.set(tff, 2);
    System.out.println(tff.x);
  }
}

This prints "1", and not "2". So, setting of a final field is actually silently ignored with setAccessible(true), for better or worse. Without setAccessible(), it will actually throw an exception. With the "final" qualifier removed from the field, it prints "2", as expected. I tested it with both latest Java 6 and on the b145 build of OpenJDK 7, and both behaves as described.

Attila.

On Jun 20, 2011, at 4:45 AM, Roel Spilker wrote:

> IIRC, disallowing the setting of final fields by reflection was never  implemented, despite several bug reports, BECAUSE it is used indeserialization.
> 
> 
> On 20-6-2011 13:09, Mark Thornton wrote:
>> On 20/06/11 11:33, Stephen Colebourne wrote:
>>> c) Try to do something clever with serialization to read the fields in
>>> manually. No - can't then store the read data as the instance variable
>>> has to be final...
>> You can use reflection to write to final fields. This permitted under
>> the memory model subject to certain restrictions.
>> 
>> Mark Thornton
>> 
>> _______________________________________________
>> Concurrency-interest mailing list
>> Concurrency-interest at cs.oswego.edu
>> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>> 
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20110620/2696325c/attachment.html>


More information about the Concurrency-interest mailing list