简体   繁体   English

使用Java Annotation进行参数验证

[英]Parameter Validation using Java Annotation

I understand, in Java we have parameters validation solution. 据我所知,在Java中我们有参数验证解决方案。 I believe JAX-RS has various annotations both for validation and data extraction. 我相信JAX-RS在验证和数据提取方面都有各种注释。 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? 我的问题是,如果我想为独立的Java应用程序实现我自己的参数验证类,我怎样才能确保只有在验证了参数时才执行方法? I am using Reflection to spot parameters with @LowerCaseCheck and then performing validation on it, but not sure where to place this validation code. 我使用Reflection来@LowerCaseCheck参数,然后对其进行验证,但不确定在哪里放置此验证代码。

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

您需要更改方法的字节代码以执行检查(或调用执行检查的方法)最简单的方法可能是使用AspectJ等面向Aspect的库。

Look at gag for an example of a library that does what you're looking for. 看看gag是否有一个可以满足您需求的库的示例。 It uses the asm bytecode manipulation library to insert validation checks at the start of annotated methods. 它使用asm字节码操作库在注释方法的开头插入验证检查。

Cant'you use Bean Validation (JSR-303) to solve your problem ? 你不能使用Bean Validation(JSR-303)来解决你的问题吗? the @Pattern(regexp) annotation seems to do just what you need. @Pattern(regexp)注释似乎可以满足您的需求。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM