Search code examples
javaclosurescriteriatype-safetyjava-7

closures mean fully type-safe criteria?


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.


Solution

  • 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.