Friday, May 6, 2011

Extracting Collection Parameterized Type at Runtime

While the parameterized type of locally declared collections is erased at compile time, it actually is possible to extract the type off of a field at runtime. Here's how it's done:

That's all there is to it. Note, this trick will not work if the collection declaration uses a wildcard or generic parameter.

Tuesday, May 3, 2011

Multi-Field Bean Validation (JSR 303)

JSR 303 is excellent, with few glaring short-comings. However, the ability to access multiple bean properties within a single field level validator is surprisingly absent. The obvious solution is to just move the validator to the class level. It's annoying and ugly, but it works. Unfortunately, the bean property path on the ConstraintViolation now points to the class and not the field where validation failed. This problem can be resolved by explicitly adding the bean property path to your validator's annotation, and doing something like the following in your validator: