简体   繁体   English

无法在Java getter方法中读取BigDecimal属性

[英]Not able to read BigDecimal property in java getter method

I am having a property discount=30 in properties file and declaring it as below in jave file : 我在属性文件中有一个属性discount = 30,并在jave文件中声明如下:

private BigDecimal discount;
public void setDiscount(BigDecimal discount) {
    this.discount = discount;
}
public BigDecimal getDiscount() {
    return discount;
}

getDiscount() is returning NULL when i try to get its value . 当我尝试获取其值时,getDiscount()返回NULL。 But I need it as BigDecimal only . 但是我只需要BigDecimal就可以了。 I dont have to declare it as String or double and type cast it though that will work. 我不必将其声明为String或double并进行类型转换,尽管这将起作用。 Using String or double is working fine except for Big Decimal. 除了Big Decimal之外,使用String或double都可以正常工作。 Please help me to fix this or what is the reason BigDecimal is not working in this case ? 请帮助我解决此问题,或者BigDecimal在这种情况下不起作用的原因是什么?

It think it will work fine, but if it returns null you didnt set it before calling the getter. 它认为它可以正常工作,但是如果返回null ,则在调用getter之前没有设置它。 If you are not able to ensure that the value is set before calling the getter, you can instantiat it in the class. 如果在调用getter之前不能确保已设置该值,则可以在类中实例化该值。 for example with 0. 例如0。

private BigDecimal discount = new BigDecimal(0);

and if you call the setter you have to do convert the value you would pass to an long or double and then use BigDecimal.valueOf() . 如果调用设置方法,则必须将值转换为long或double值,然后使用BigDecimal.valueOf()

In Properties files its always returned as String. 在属性文件中,它始终以字符串形式返回。

While getting the data from properties file convert it into BigDecimal then use it. 从属性文件获取数据时,将其转换为BigDecimal,然后使用它。

SelectClient c= new SelectClient();
BigDecimal b = new BigDecimal(prop.getProperty("data"));
c.setDiscount(b);
System.out.println(c.getDiscount());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM