要使用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注解來校驗參數是否為空。如果參數為空,會打印出相應的錯誤信息。