如何在Java中使用枚举作为参数创建对象

时间:2019-02-20 09:22:52

标签: java enums

我上课

public enum CustomerType {
    GOLD, SILVER, IRON, RUSTY

}

和另一个班级:

@Entity

公共类Customer实现了可序列化的{

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String firstName;
private String lastName;
private CustomerType type;


public Customer(){};
public Customer(String firstName, String lastName){
    this.firstName = firstName;
    this.lastName = lastName;
}
public Customer(String firstName, String lastName, CustomerType type){
    this.firstName = firstName;
    this.lastName = lastName;
    this.type = type;
}

public String getFirstName(){ return firstName;}
public String getLastName(){ return lastName;}
public Integer getId() {   return id; }
public CustomerType getType(){ return type;}

public void setId(Integer id) { this.id = id;}
public void setFirstName(String firstName){this.firstName = firstName;}
public void setLastName(String lastName ){this.lastName = lastName;}
public void setType(CustomerType type){this.type = type;}


@Override
public int hashCode() {
    int hash = 0;
    hash += (id != null ? id.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof Customer)) {
        return false;
    }
    Customer other = (Customer) object;
    if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "entity.Customer[ id=" + id + " ]";
}

}

我有一个构造函数,其参数为firstName,lastName,CustomerType类型

我要在另一个班级中创建这样的客户

Customer c1 = new Customer("ida", "heartless", GOLD); 

但是它不会像这样放枚举参数。如何正确使用枚举?我想念的是什么?

2 个答案:

答案 0 :(得分:2)

看起来您只需要在Customer类中导入即可。 然后它应该看起来像这样:

Customer c1 = new Customer("ida", "heartless", CustomerType.GOLD); 

答案 1 :(得分:1)

您需要添加CustomerType.GOLD而不是GOLD