首页 > 解决方案 > 如何在Java中创建一个以枚举为参数的对象

问题描述

我有一堂课

public enum CustomerType {
    GOLD, SILVER, IRON, RUSTY

}

和另一个类:

@Entity

公共类客户实现可序列化{

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); 

但它只是不会让像这样放置枚举参数。我怎样才能正确使用枚举?我错过了什么?

标签: javaenums

解决方案


看起来你只需要在你的Customer类中导入。之后它应该看起来像这样:

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

推荐阅读