lundi 26 septembre 2016

Passign attribute name as parameter automatically in Java-8

I would like to have a method to validate fields kind of

protected void validate(String field, String fieldName){
  if (field==null || field.isEmpty){
    throw new IllegalArgumentException("Parameter " + fieldName + " cannot be empty");
  }
}

and use in my class for example

class Foo {
  private String x;
  private String y;

  ...

  public void validateAll(){
    validate(x, "x");
    validate(y, "y");
  }
}

It would be great to use in this way

  public void validateAll(){
    validate(x);
    validate(y);
  }

and let the compiler pass the name of the variable automatically to validate(field, fieldName) method

How can I achive this in Java-8 ?





Aucun commentaire:

Enregistrer un commentaire