要使用Java注解来校验参数是否为空,可以使用javax.validation.constraints包中的注解来实现。具体步骤如下:
public class MyClass {
@NotNull
private String myParameter;
// getters and setters
}
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.ConstraintViolation;
public class MyClassValidator {
public void validateMyParameter(MyClass myClass) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<MyClass>> violations = validator.validate(myClass);
if (!violations.isEmpty()) {
for (ConstraintViolation<MyClass> violation : violations) {
System.out.println(violation.getMessage());
}
}
}
}
public class Main {
public static void main(String[] args) {
MyClass myClass = new MyClass();
MyClassValidator validator = new MyClassValidator();
myClass.setMyParameter(null);
validator.validateMyParameter(myClass);
}
}
这样就可以通过Java注解来校验参数是否为空。如果参数为空,会打印出相应的错误信息。