Validation in constructor java

Java Bean Validation — Using constraints on constructor and method return values

In the last tutorial, we saw how to validator method/constructor parameters. In this tutorial we will see how to validator method/constructor return values.

Example

Using constraints on method return values

We can validate method return value to make sure that all post condition are met after calling the method.

package com.logicbig.example; import javax.validation.*; import javax.validation.constraints.Size; import javax.validation.executable.ExecutableValidator; import java.beans.IntrospectionException; import java.lang.reflect.Method; import java.util.Set; public class MethodReturnValidationExample < private static class TestBean < @Size(min = 5) public int[] findNumbers () < return new int[]; > > public static void main (String[] args) throws NoSuchMethodException, IntrospectionException < TestBean test = new TestBean(); int[] testNumbers = test.findNumbers(); Method method = TestBean.class.getDeclaredMethod("findNumbers"); Validator validator = getValidator(); ExecutableValidator executableValidator = validator.forExecutables(); Set> violations = executableValidator.validateReturnValue(test, method, testNumbers); if (violations.size() > 0) < violations.stream().forEach(MethodReturnValidationExample::printError); >else < //proceed using Order object >> private static Validator getValidator() < Configurationconfig = Validation.byDefaultProvider().configure(); ValidatorFactory factory = config.buildValidatorFactory(); Validator validator = factory.getValidator(); factory.close(); return validator; > private static void printError ( ConstraintViolation violation) < System.out.println(violation.getPropertyPath() + " " + violation.getMessage()); >>

Output

findNumbers. size must be between 5 and 2147483647

Using constraints on constructor return value.

Constructors don’t return values like method do but they return a newly instantiated object. We can find out validation violation on new object to make sure that all post conditions are met after the object creation.

Читайте также:  Эффекты кнопки при наведении css

Following example creates a custom constraints ‘ValidOrder’ to validate the returned constructor value. The assumed requirement in this example is: the total order prices should be $50 or more.

package com.logicbig.example; import javax.validation.*; import javax.validation.executable.ExecutableValidator; import java.lang.annotation.*; import java.lang.reflect.Constructor; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Set; public class ConstructorReturnValidationExample < public static class Order < private final BigDecimal price; private final BigDecimal quantity; @ValidOrder public Order (BigDecimal price, BigDecimal quantity) < this.price = price; this.quantity = quantity; >public BigDecimal getPrice () < return price; >public BigDecimal getQuantity () < return quantity; >public BigDecimal getTotalPrice () < return (price != null && quantity != null ? price.multiply(quantity) : BigDecimal.ZERO) .setScale(2, RoundingMode.CEILING); >> public static void main (String[] args) throws NoSuchMethodException < Order order = new Order(new BigDecimal(4.5), new BigDecimal(10)); Constructorconstructor = Order.class.getConstructor(BigDecimal.class, BigDecimal.class); Validator validator = getValidator(); ExecutableValidator executableValidator = validator.forExecutables(); Set constraintViolations = executableValidator.validateConstructorReturnValue(constructor, order); if (constraintViolations.size() > 0) < constraintViolations.stream().forEach( ConstructorReturnValidationExample::printError); >else < //proceed using order System.out.println(order); >> private static Validator getValidator() < Configuration[] groups () default <>; Class[] payload () default <>; > public static class OrderValidator implements ConstraintValidator  < @Override public void initialize (ValidOrder constraintAnnotation) < >@Override public boolean isValid (Order order, ConstraintValidatorContext context) < if (order.getPrice() == null || order.getQuantity() == null) < return false; >return order.getTotalPrice() .compareTo(new BigDecimal(50)) >= 0; > > >

Output

Order. total price must be 50 or greater for online order. Found: 45.00

Example Project

Dependencies and Technologies Used:

    hibernate-validator 6.2.0.Final (Hibernate’s Jakarta Bean Validation reference implementation)
    Version Compatibility: 5.0.0.Final — 6.2.0.Final Version List

Источник

Java Bean Validation — Using constraints on constructor and method parameters

We can do validations on constructor parameters or method parameters by placing the constraints just right before the parameters.

ExecutableValidator is used perform such validation.

Definition of ExecutableValidator

package javax.validation.executable; . public interface ExecutableValidator < Set validateParameters( T object, Method method, Object[] parameterValues, Class. groups); Set validateReturnValue( T object, Method method, Object returnValue, Class. groups); Set validateConstructorParameters( Constructor constructor, Object[] parameterValues, Class. groups); Set validateConstructorReturnValue( Constructor constructor, T createdObject, Class. groups); >

As seen above ExecutableValidator can be used to validate constructor/method parameters and their return values. In this example we will focus on only validator parameters.

Examples

Using constraints on constructor parameter

We can validate constructor parameters before the constructor is invoked so that we can be sure that all preconditions are met before calling a constructor.

package com.logicbig.example; import javax.validation.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.executable.ExecutableValidator; import java.lang.reflect.Constructor; import java.util.Comparator; import java.util.Set; public class ConstructorParamValidationExample < private static class User < private final String name; private final String phone; public User(@NotNull String name, @NotNull @Pattern(regexp = "(\\d)-\\d-\\d", message = "must match 111-111-1111 format") String phone) < this.name = name; this.phone = phone; >public String getName() < return name; >public String getPhone() < return phone; >> public static void main(String[] args) throws NoSuchMethodException < Validator validator = getValidator(); Constructorconstructor = User.class.getConstructor(String.class, String.class); ExecutableValidator executableValidator = validator.forExecutables(); String userName = null; String userPhone = "223-223-222"; Set constraintViolations = executableValidator.validateConstructorParameters(constructor, new Object[]); if (constraintViolations.size() > 0) < constraintViolations.stream().sorted(Comparator.comparing(o ->o.getPropertyPath().toString())) .forEach(ConstructorParamValidationExample::printError); > else < User user = new User(userName, userPhone); System.out.println(user); >> private static Validator getValidator() < Configurationconfig = Validation.byDefaultProvider().configure(); ValidatorFactory factory = config.buildValidatorFactory(); Validator validator = factory.getValidator(); factory.close(); return validator; > private static void printError( ConstraintViolation violation) < System.out.println(violation.getPropertyPath() + " " + violation.getMessage()); >>

Output

User.arg0 must not be null
User.arg1 must match 111-111-1111 format

Using constraints on method parameters

Just like constrictors, we can also find out validation violations on method parameter before the method is invoked. That way we can make sure that all preconditions are satisfied before calling a method.

package com.logicbig.example; import javax.validation.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.validation.executable.ExecutableValidator; import java.lang.reflect.Method; import java.util.Comparator; import java.util.Set; public class MethodParamValidationExample < private static class Task < public void run (@Size(min = 3, max = 20) String name, @NotNull Runnable runnable) < System.out.println("starting task synchronously: " + name); runnable.run(); >> public static void main (String[] args) throws NoSuchMethodException < Validator validator = getValidator(); Method method = Task.class.getDeclaredMethod("run", new Class[]); ExecutableValidator executableValidator = validator.forExecutables(); Task task = new Task(); String taskName = "a"; Runnable runnable = null; Set> violations = executableValidator.validateParameters(task, method, new Object[]); if (violations.size() > 0) < violations.stream().sorted(Comparator.comparing(o ->o.getPropertyPath().toString())) .forEach(MethodParamValidationExample::printError); > else < task.run(taskName, runnable); >> private static Validator getValidator() < Configurationconfig = Validation.byDefaultProvider().configure(); ValidatorFactory factory = config.buildValidatorFactory(); Validator validator = factory.getValidator(); factory.close(); return validator; > private static void printError ( ConstraintViolation violation) < System.out.println(violation.getPropertyPath() + " " + violation.getMessage()); >>

Output

run.arg0 size must be between 3 and 20
run.arg1 must not be null

Example Project

Dependencies and Technologies Used:

    hibernate-validator 6.2.0.Final (Hibernate’s Jakarta Bean Validation reference implementation)
    Version Compatibility: 5.0.0.Final — 6.2.0.Final Version List

Versions in green have been tested.

Источник

Оцените статью