我通过pojo的getter方法在一个对象中获取量
但是那个数量的getter方法返回类型在pojo中设置为字符串
如下所示

//setting need to be done in pojo
private String amount;

    public String getAmount() {
        return amount;
    }


在下面说,有一个对象h,我正在像检索它

h.getAmount()


现在我需要开发一个验证器来验证该金额
是整数类型,如果不是,则将引发异常
请告知我如何开发一种单独的方法来检查是否
金额是否为整数,并以此为基础
将返回true或false,如下所示

// Validate the amount is in integer
private boolean isValidAmount (String Amount) {
    boolean valid = false;
//code to check whether the Amount is integer or not, if integer then
//return true else return false
}


我已经更新了该帖子,因为它引发了数字格式异常,请告知

最佳答案

您可以尝试解析它,并在解析成功后返回true。

try {
    Integer.parseInt(amount);
    return true;
} catch (NumberFormatException e) {
    return false;
}


编辑

我只是重新阅读了这个问题,并注意到,似乎您唯一想使用此true / false值要做的就是在无法解析字符串的情况下引发异常。在这种情况下,您可以摆脱该布尔中间人:

try {
    Integer.parseInt(amount);
} catch (NumberFormatException e) {
    throw new MyWhateverException(amount);
}

09-07 10:40
查看更多