users@glassfish.java.net

Re: Container injected _at_Resource fields should be declared "volatile"?

From: <glassfish_at_javadesktop.org>
Date: Mon, 19 Nov 2007 11:36:01 PST

> I don't believe it is correct that reflection can set 'final' fields.

Just to be complete...

[code]
FinalTest.java:
public class FinalTest {
        public final int n;

        public FinalTest() {
                n = 1;
        }

        public int getN() {
                return n;
        }
}

ReflectTest.java:
import java.lang.reflect.Field;

public class ReflectTest {
        public static void main(String args[]) throws Exception {
                FinalTest f = new FinalTest();

                System.out.println(f.getN());

                Field[] fields = f.getClass().getDeclaredFields();

                // This resets final
                fields[0].setAccessible(true);
                fields[0].set(f, 20);

                System.out.println(f.getN());
        }
}
[/code]

Final is both a runtime and compile time check. The "setAccessible" call resets the flag to prevent the runtime exception (otherwise the following set gives an exception). But you still can't actually compile Java source code that accesses final field due to a compile time check.

> For that matter, 'final' is incompatible with serialization.

Actually, this whole mechanism is there for serialization. There's no mention of final being incompatible with serialization. Deserializing an object can be, for most intents and purposes, similar to constructing a new object, so there's no reason we shouldn't be able to serialize objects with final fields.
[Message sent by forum member 'whartung' (whartung)]

http://forums.java.net/jive/thread.jspa?messageID=246171