Abidi
Abidi

Reputation: 7996

Parameter Validation using Java Annotation

I understand, in Java we have parameters validation solution. I believe JAX-RS has various annotations both for validation and data extraction. My question is, if I want to implement my own parameter validation class for a standalone Java application, how would I make sure that a method is executed only when its parameters have been validated? I am using Reflection to spot parameters with @LowerCaseCheck and then performing validation on it, but not sure where to place this validation code.

public void print(@LowerCaseCheck String lowerCaseString) {
  ....
}

Upvotes: 0

Views: 435

Answers (3)

Frederic Close
Frederic Close

Reputation: 9639

Cant'you use Bean Validation (JSR-303) to solve your problem ? the @Pattern(regexp) annotation seems to do just what you need.

public void print(@Pattern(regexp = "^[a-z]*$") String lowerCaseString) {
  ....
}

Upvotes: 0

Sam Marsh
Sam Marsh

Reputation: 166

Look at gag for an example of a library that does what you're looking for. It uses the asm bytecode manipulation library to insert validation checks at the start of annotated methods.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533500

You need to change the byte code of the method to perform the check (or call a method which performs the check) The simplest way to do this might be to use an Aspect orientated library like AspectJ.

Upvotes: 2

Related Questions