I’m very new to Java but I’ve been developing a habit to use final wherever possible declaring immutability which i think is a good thing. (Consider f#)
I’ve read that JPA does not support final fields. Hibernate, TopLink? I’m not sure about these but i prefer JPA for now.
Is that even possible theoretically – let’s say through reflection – to modify final fields after creation? My guess would be… NO 🙂
What would be certainly possible for a persistence solution is to support constructors with parameters. At least i see no reason that would make this impossible. Mapping would be a little tricky i guess.
This is an alternative solution.
Suggestions?
EDIT: I’m not familiar with the exact definition for immutable so i used it in this post intuitively. Declaring Immutability here means declaring that a field cannot be changed. Sorry for the misunderstanding.
Object immutability (note the difference between an immutable object, and declaring a field final – an object is ONLY immutable if ALL fields are final, thus the object’s state can’t change after creation) is a very sensitive topic. I like them myself, and hibernate supports them through @Immutable.
Don’t know about it’s status in JPA 2, but to answer the question about final fields: you CAN change their values using reflection – but reflection is severly limited in a Java EE environment.
To enlighten the main problem: if your POJOs are immutable, then how would a persistent solution recreate the objects? Let’s say you have two final int fields, and a constructor to initialize them. The persistence layer cannot have any information about their order, or their names (as field and parameter names are erased during compiling).
Koshuke posted a blog about this (in relation to JAXB supporting immutable beans), but can’t find it right now.