现在,我有一个带字段的类。
@Entity
public class Fuel {
@Id @GeneratedValue
private Long id;
private boolean diesel;
private boolean gasoline;
private boolean etanhol;
private boolean cng;
private boolean electric;
public Fuel() {
// this form used by Hibernate
}
public List<String> getDeclaredFields() {
List<String> fieldList = new ArrayList<String>();
for(Field field : Fuel.class.getDeclaredFields()){
if(!field.getName().contains("_") && !field.getName().equals("id") && !field.getName().equals("serialVersionUID") ) {
fieldList.add(field.getName());
}
Collections.sort(fieldList);
}
return fieldList;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public boolean isDiesel() {
return diesel;
}
public void setDiesel(boolean diesel) {
this.diesel = diesel;
}
public boolean isGasoline() {
return gasoline;
}
public void setGasoline(boolean gasoline) {
this.gasoline = gasoline;
}
public boolean isEtanhol() {
return etanhol;
}
public void setEtanhol(boolean etanhol) {
this.etanhol = etanhol;
}
public boolean isCng() {
return cng;
}
public void setCng(boolean cng) {
this.cng = cng;
}
public boolean isElectric() {
return electric;
}
public void setElectric(boolean electric) {
this.electric = electric;
}
}
我认为这是有道理的,但是当我问另一个问题时(可能是一个愚蠢的例子,因为只能有自动或手动变速箱)https://stackoverflow.com/questions/11747644/selectonemenu-from-declared-fields-list-在-pojo中,一位用户建议我改用枚举。像这样:
public enum Fuel {
DIESEL("diesel"),
GASOLINE("gasoline"),
ETANHOL("etanhol"),
CNG("cng"),
ELECTRIC("electric");
private String label;
private Fuel(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
}
然而,由于市场上存在混合动力车(如丰田普锐斯),父类将以这种方式实现布尔类:
private Fuel fuel = new Fuel();
如果以这种方式使用枚举列表:
private List<Fuel> fuelList = new ArrayList<Fuel>();
最佳做法是什么?请记住,我可能有 100 种不同的燃料(例如 =)。不要忘记它是一个实体,因此会保存在数据库中。
提前感谢=)