我正在用java开发一个小的验证器。我想验证输入值是 0 还是干脆为空。如果它为空或 0,我想得到一个例外。所以我的代码正在寻找,我知道它还没有完成,但我不知道如何实现它。感谢您的帮助!
public boolean isValid(final AbstractObject value) {
if (value instanceof Bank) {
final Bank bank = (Bank) value;
final ApplicationContext appContext = this.getApplicationContext();
final BankService service = (BankService) appContext.getBean("myStoreService");
final Map<String, Object> namedParam = new HashMap<String, Object>();
namedParam.put(Bank.PROPERTY_IBAN, bank.getIban());
namedParam.put(Bank.PROPERTY_BIC, bank.getBix());
namedParam.put(PersistentObject.PARAMETER_DIFFERENT_STATUS, PersistentObject.STATUS_DELETED);
final Integer count = service.countBankByQuery(namedParam);
if (count <= 0) {
return false;
}
}
return false;
}
从你的代码
final Integer count = service.countBankByQuery(namedParam);
if (count <= 0) {
return false;
}
Integer
不能是"空的",但可以null
。
因此,只需检查这些可能的值
if( count == null || count == 0)
注意:请注意,如果您不检查它是否null
,count == 0
应该抛出一个NullPointerException
,因为它实际上是count.intValue() == 0
,不能在空实例上调用方法。
Java 8解决方案:
final Integer count = service.countBankByQuery(namedParam);
if (Optional.ofNullable(count).orElse(0).intValue() == 0) {
throw new Excepton();
}
带有番石榴的 Java 替代解决方案 可选:
final Integer count = service.countBankByQuery(namedParam);
if (Optional.fromNullable(count).or(0).intValue() == 0) {
throw new Excepton();
}
或者编写你自己的通用对象包装器类,即:
public class MyOptional<T> implements Serializable...
您需要先检查值判断是value==0
还是value==null
,然后扔new Exception()
你应该创建一个"自定义"异常并检查它是否为空
这是处理实际代码的例外,只需创建一个新类并将该代码放入其中,它只是一个要求字符串的构造函数
public class emptyOrZeroIntegerException extends Exception{
public emptyOrZeroIntegerException()
{
super();
// TODO Auto-generated constructor stub
}
public emptyOrZeroIntegerException(String message)
{
super(message);
// TODO Auto-generated constructor stub
}
下面是修改为使用异常的代码
public boolean isValid(final AbstractObject value) throws emptyOrZeroIntegerException {
if (value instanceof Bank) {
final Bank bank = (Bank) value;
final ApplicationContext appContext = this.getApplicationContext();
final BankService service = (BankService) appContext.getBean("myStoreService");
final Map<String, Object> namedParam = new HashMap<String, Object>();
namedParam.put(Bank.PROPERTY_IBAN, bank.getIban());
namedParam.put(Bank.PROPERTY_BIC, bank.getBix());
namedParam.put(PersistentObject.PARAMETER_DIFFERENT_STATUS, PersistentObject.STATUS_DELETED);
final Integer count = service.countBankByQuery(namedParam);
//Check if empty here and throw new Exception
if (count <= 0) {
throw new emptyOrZeroIntegerException("Number not valid");
}
}
return false;
}