我有一个使用枚举类型的 java 对象
public class Deal{
public enum PriceType {
fixed, hour, month, year
}
@Element(name = "price-type", required = false)
private PriceType priceType;
}
这个对象是从一些 API 中填充的,我在具有字符串类型变量的数据库对象中检索它
MyDeal{
private String priceType;
public String getPriceType() {
return priceType;
}
public void setPriceType(String priceType) {
this.priceType = priceType == null ? null : priceType.trim();
}
}
为什么我不能像这样设置数据库对象
List<Deal>deals = dealResource.getAll();
MyDeal myDeal = new myDeal();
for (Deal deal : deals) {
myDeal.setPriceType(deal.getPriceType());
}
最佳答案
您不能直接将 PriceType
设置为字符串。你需要做这样的事情
for (Deal deal : deals) {
myDeal.setPriceType(deal.getPriceType().name()); // name() will get that name of the enum as a String
}
尽管 for
循环看起来有严重缺陷。您只需一遍又一遍地覆盖 myDeal
中的 priceType
。
关于java - 如何将枚举类型设置为字符串类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19537803/