2
votes

I have a bean class

BeanClass {

  <prop1>;
  <prop2>;
  <prop3>;

  //getters and setters
  ...
}

and a validations utility:

Validations {

  static void notNull(Object value, ValidationResult result) {
    if (...) {
      ...
    }
  }

  static void doesNotExceedMaxLength(Object value, int max, ValidationResult result) {
    if (...) {
      ...
    }
 }

I would like to generate a Validator like below -

BeanValidator {

  ValidationResult validate(BeanClass bean) {
    ValidationResult validationResult = new ValidationResult();

    //prop1, prop3 are mandatory...
    notNull(bean.getProp1(), validationResult);
    notNull(bean.getProp3(), validationResult);

    //prop2 must not be more than 255 characters in length
    doesNotExceedMaxLength(bean.getProp2(), 255, validationResult)

    return validationResult;
  }
}

The decision of what fields are mandatory and for which values must not exceed a certain number will made at run time looking at the bean class.

How can I do this with Byte Buddy?

1

1 Answers

1
votes

I do not think that you want to use Byte Buddy for this purpose. This is what the reflection API is made for. Using Byte Buddy does not grant you any performance benefit and as Byte Buddy does not create any source code, you will neither document your application further.

Why did you want to use code generation for implementing such a validator?