Saturday, August 16, 2008

How to construct immutable objects using reflection

John O'Hanley argues that Javabeans should not be used with database frameworks. The reason various ORM frameworks use Javabeans is because they need to be able to construct objects using reflection. Javabeans provided this capability, whereas constructors were hard to introspect (at least as of Java 1.4) because the compiler saves only the types of method arguments, and not their names. The need to reflectively set properties by name is a legitimate one. Javabeans, by virtue of their extreme mutability, are certainly a problematic approach. But rather than discarding Javabeans and ORM entirely, John, you should propose a solution for those who want ORM. Then you will be taken more seriously. Perhaps Java 5 annotations finally give us enough capability to construct immutable objects reflectively. A constructor could be given an annotation that tells the ORM framework how its arguments map to entity fields.