我正在开发一个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;
}
答案 0 :(得分:2)
从你的代码
final Integer count = service.countBankByQuery(namedParam);
if (count <= 0) {
return false;
}
Integer
无法排空&#34;但可以是null
。
所以只需检查那些可能的值
if( count == null || count == 0)
注意:
请注意count == 0
如果不检查NullPointerException
是不是null
,count.intValue() == 0
,$unwind
,$match
,$sort
调用null实例。
答案 1 :(得分:1)
Java 8解决方案:
final Integer count = service.countBankByQuery(namedParam);
if (Optional.ofNullable(count).orElse(0).intValue() == 0) {
throw new Excepton();
}
使用Guava的Java替代解决方案可选:
final Integer count = service.countBankByQuery(namedParam);
if (Optional.fromNullable(count).or(0).intValue() == 0) {
throw new Excepton();
}
或者编写自己的一般化对象包装类,即:
public class MyOptional<T> implements Serializable...
答案 2 :(得分:-1)
您需要首先判断值是value==0
还是value==null
然后判断
抛出new Exception()
答案 3 :(得分:-1)
您应该创建一个“自定义”Exception并检查它是否为空
这是使用您的实际代码的异常,只需创建一个新类并将该代码放入其中,它只是一个要求字符串的构造函数
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;
}
这是您修改的代码以使用Exception
<?php
$counter = 1;
foreach($results as $result){
?>
<div id="box<?php echo $counter; ?>">
</div>
<?php $counter++;
} ?>