当我尝试使用Apache beanUtils在我的bean中设置一个日期属性时,它失败了"类#34中没有setter方法。非日期属性设置正确。
以下代码以Property 'availableFrom' has no setter method in class 'class com.brightgreenstar.entities.CapitalAsset'
if (value instanceof String){
if ((key.equals("lastUpdatedDate")) || (key.equals("availableFrom")) || (key.equals("availableTo"))|| (key.equals("purchaseDate"))) {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss ZZZZ");
Date date = df.parse((String)value);
PropertyUtils.setProperty(asset,key,date);
// PropertyUtils.setSimpleProperty(asset,key,value); // Also fails for dates
}else{
PropertyUtils.setSimpleProperty(asset,key,value);
}
} else{
PropertyUtils.setSimpleProperty(asset,key,value);
}
如果我不使用PropertyUtils更新日期属性并直接调用setter(例如asset.setAvailableFrom
),那么它可以正常工作。这对我来说是可行的解决方案,但我更喜欢使用PropertyUtils。
if (value instanceof String){
if ((key.equals("lastUpdatedDate")) || (key.equals("availableFrom")) || (key.equals("availableTo"))|| (key.equals("purchaseDate"))) {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss ZZZZ");
Date date = df.parse((String)value);
if (key.equals("availableFrom")){
asset.setAvailableFrom(date); // This works
}
}else{
PropertyUtils.setSimpleProperty(asset,key,value);
}
}else{
PropertyUtils.setSimpleProperty(asset,key,value);
}
任何建议表示赞赏。
CapitalAsset bean:
public class CapitalAsset {
private Date availableFrom;
private Date availableTo;
public String getAvailableFrom(){
try {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss z");
return df.format(availableFrom);
} catch (Exception e) {
return "";
}
}
public void setAvailableFrom(Date availableFrom) {
this.availableFrom = availableFrom;
}
public String getAvailableTo(){
try {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss z");
return df.format(availableTo);
} catch (Exception e) {
return "";
}
}
public void setAvailableTo(Date availableTo) {
this.availableTo = availableTo;
}
}
答案 0 :(得分:1)
需要包含一个返回日期的getter:
public Date getAvailableFrom(){
return availableFrom;
}