views:

200

answers:

2

combining closures (FCM) and generics, would it be possible to have fully type-safe criteria.

// The following works without a cast as Foo.id is a 'long' field.
List<Long> ids = session.createCriteria(Foo.class)
                        .setProjection(Foo#id)
                        .list();

// The following is a compilation error, as Foo.bar is defined as an int, and not a string
session.createCriteria(Foo.class)
       .addRestriction(Restrictions.eq(Foo#bar,"blah"))
       .list();

I've read the JPA 2.0 spec for type-safe criteria. But its still somewhat lacking.

Besides, I'm just using criteria here as an example of improving the type-safety of code in general. I used the static typing of java heavily to let me code faster. But as a result I get bitten now and then by the parts of my code that ignore typing. For example HQL queries.

+2  A: 

The code you're describing does not use closures but field literals (method literals). Like the good old class literal. These could help in a criteria API. The JPA 2 source code generation work-around for a type-safe query interface could be replaced with it. If it will be part of JDK7.

Thomas Jung
thanks, I just wanted to get a second pair of eyes on this. by "using closures" I meant the field literals that come along with FCM. I sure hope Sun sticks with that proposal, as it provides a heck of alot more than just closures to the table.
DragonFax
+1  A: 

As Thomas points out, this doesn't strictly require closures. It's all up in the air at the moment, given no-one knows quite what proposal is being looked at. It's not clear if FCM is actually the basis of the proposal, particularly given that Stephen Colebourne seemed to be as susprised as anyone about the announcement.

A lot of people are pointing at Neal Gafter's mysteriously-revised-more-or-less-right-as-the-Devoxx-presentation-announcing-closures-was-being-given spec as a hint as to what form closures might take. Mind you, the revised proposal looks (aesthetically) rather like FCM!

That spec does include the kind of references you refer to (under 'Method References' in the above line), and of course FCM has the same. Yes, this would definitely make you suggest possible. My very first thought when reading about this was how it would affect JPA/Hibernate, and/or our own abstraction layers around same, in this regard. Typesafe, refactorable method references in your criteria? Hell yeah.

Cowan
Method literals (with some constraints) are not to hard to implement with a recorder (see easyMock). Field literals are harder (see JPA2). There is no reason why method and literal are not in Java now. Even javadoc has them.
Thomas Jung