我必须对我的类的6个属性进行空字符串检查,该属性共有7个属性

时间:2016-09-20 09:09:27

标签: java

我必须对我的类的6个属性进行空字符串检查,这些属性共有7个属性,有没有更好的方法可以做而不是分别检查每个属性?

3 个答案:

答案 0 :(得分:0)

你可以在课堂上制作一个常用的方法

class MyClass {
  String attr1, attr2, attr3;

  public boolean isValid() {
    return !attr1.isEmpty() && !attr2.isEmpty()  ;
  }
}

答案 1 :(得分:0)

一种选择是使用Hibernate Validator api,你可以在6个参数上设置@NotNull属性。 注意:如果在许多地方需要框架或者已经在使用框架,那么不仅应该使用框架。

public class Abc{

   @NotNull
   private String var1;

   @NotNull
   @Size(min = 1, max = 4)
   private String var2;

   @Min(5)
   private int var3;

   // ...
}

答案 2 :(得分:0)

如果你使用的是java 8,你可以这样做:

创建泛型类Validator:

public class Validator<T> {

private T t;
private List<Throwable> exceptions = new ArrayList<>();

private Validator(T t) {
    this.t = t;
}

public static <T> Validator<T> of(final T t) {
    return new Validator<T>(t);
}

public <U> Validator<T> validate(final Function<T, U> projection, final Predicate<U> filter, final String message) {

    if (!filter.test(projection.apply(t))) {
        this.exceptions.add(new IllegalStateException(message));
    }
    return this;
}

public List<Throwable> get() {
   return exceptions;
  }
}
验证器类中的

YourObject yourObject = new yourObject("attr1", "attr2", "attr3");

List<Throwable> result = Validator.of(yourObject)
    .validate(YourObject::getAttr1, a -> !a.isEmpty(), "attr1 should not be empty")
    .validate(YourObject::getAttr2, a -> !a.isEmpty(), "attr2 should not be empty")
    .validate(YourObject::getAttr3, a -> !a.isEmpty(), "attr3 should not be empty").get();

检查结果是否为空。

如果您使用的是java 7,则可以调整以前的代码:

public class StringValidator {

private List<Throwable> exceptions = new ArrayList<>();

private Validator() {

}

public static StringValidator instance() {
 return new Validator();
}

public  StringValidator validate(final String value, final String message) {

 if (value.isEmpty()) {
    this.exceptions.add(new IllegalStateException(message));
 }
 return this;
}

public List<Throwable> get() {
 return exceptions;
 }
}
验证器类中的

YourObject yourObject = new yourObject("attr1", "attr2", "attr3");

List<Throwable> result = Validator.instance()
    .validate(yourObject.getAttr1(), "attr1 should not be empty")
    .validate(yourObject.getAttr2(), "attr2 should not be empty")
    .validate(yourObject.getAttr3(), "attr3 should not be empty").get();
相关问题