views:

270

answers:

3

I want to add validations to a Java Bean. For example, I want to do the following:

@MaxLength(50)
@RequiredField
public void setEmployeeName(String name){
   .....
}

I know I can write code that gets the validations for a specific method by calling method.getDeclaredAnnotation after all the bean values have been set. I would like to avoid writing this code

Is there anything in Java6 that gives standard validations via annotations? Do I need aspectj to invoke these annotations?

thanks in advance.

+1  A: 

You can use Bean Validation Framework. Here is short overview http://relation.to/Bloggers/BeanValidationSneakPeekPartI

eugener
A: 

take a look at JSR 303. The RI (Reference Implementation) is here, with also a nice tutorial. And no, you don't need AspectJ.

dfa
A: 

The only way you'll be able to do this is through reflections and a custom validation utility/interceptor/proxy. JSR 303 and JSR 305 were proposed to introduce similar functionality, but nothing like this exists.

One of the problems you'll run into is that these annotations need to be handled at some sort of framework level, or at a minimum, intercepted before some sort of invoked action. The two most common sense, brute force ways of doing this would be done either by creating a utility, or by validating pre-invoke in an invocation handler (proxy).

The reality is that unless this is built into Spring, Struts, Guice, Java itself, etc., you're just creating unnecessary overhead and you're better off checking for validation bounds on demand.

Droo