0

I want to write validation for all fields of a Java bean.

My method for blank validation is

private static boolean isBlank(String value) {
     return value.equalsIgnoreCase("")?true:false;
}

I am passing all properties of bean to the isBlank() method, and want to get out of this method when any property is blank. like this-

public static boolean isValid(User user) {
isBlank(user.getPersonId())?return false:{I want to stay here and check next};
isBlank(user.getEmployeeNumber());
isBlank(user.getFullName());
.
.
}

How can I achieve this in minimum possible code.

4

4 回答 4

1

你不需要isBlank(String value),试试这个:

public static boolean isValid(User user){
return !(user.getPersonId().isEmpty()
    || user.getEmployeeNumber.isEmpty()
    || user.getFullName().isEmpty());

}

于 2013-10-24T06:28:18.200 回答
0

使用您的代码:

public static boolean isValid(User user) {
  if (isBlank(user.getPersonId())) return false;
  if (isBlank(user.getEmployeeNumber())) return false;
  if (isBlank(user.getFullName())) return false;
.
.
  return true;
}

或者:

public static boolean isValid(User user) {
  if (isBlank(user.getPersonId()) ||
      isBlank(user.getEmployeeNumber()) ||
      isBlank(user.getFullName())) return false;
  return true;
}

如果您想避免编写所有代码,您可以使用反射来动态发现类字段。如果您使用的是 bean 范例,则可以使用Introspector类。这里有一个教程(我在 Oracle 网站上找不到那个)。

于 2013-10-24T06:28:30.300 回答
0

您可以在项目中使用 Apachecommons-lang并添加此静态导入:

import static org.apache.commons.lang.StringUtils.isNotEmpty;

那么你的代码可以是这样的:

public static boolean isValid(User user) {
    return isNotEmpty(user.getPersonId()) && isNotEmpty(user.getEmployeeNumber()) && isNotEmpty(user.getFullName());
}

Apache Commons Lang 可以在此处下载- 只需确保将其作为库添加到您的项目中,以便您可以使用名为StringUtils.

于 2013-10-24T06:26:51.713 回答
-1

做同样事情的理想方法是使用反射。这样您就不需要在每个变量上显式调用,并且如果删除或添加任何变量,您就不会紧密耦合到相同的变量。

使用反射,循环所有可用变量并从 try catch 块调用 isBlank。

private static boolean isBlank(String value) {
      boolean flag = value.equalsIgnoreCase(""); 
      if(flag){
        throw new Exception(e);
     }
retrun flag;

}
于 2013-10-24T06:07:39.717 回答