如何在构造函数中设置对象枚举类型?

时间:2016-03-25 11:17:09

标签: java enums

我有以下课程:

public class Owner {

  private final Integer id;
  private final OwnerType type;

  public Owner(Integer iId, Enum eType) {
      this.id= iId;
      this.lastName = lName;
      this.type = eType // how should that work?
  } 

}

并且

public enum OwnerType {
    HUMAN,INSTITUTION   
}

我通过以下方式致电:

try {
    File file = new File("resources/Owner.txt");
    Scanner fileContent = new Scanner(file);
    while (fileContent.hasNextLine()) {
            String[] person = fileContent.nextLine().split(" ");
            this.data.add(new Owner(owner[0],owner[1]));
        }
    } catch (FileNotFoundException err){
        System.out.println(err);
    }

其中Owner.txt的格式为:

ID TYPE

就像那样:

1 HUMAN
2 INSTITUTION

我的问题是:

当我调用以下内容时,如何指定所有者对象的type属性?

new Owner(owner[0],owner[1]) 

2 个答案:

答案 0 :(得分:2)

这里有两个问题。

首先,Owner的构造函数应该收到OwnerType,而不仅仅是Enum

public Owner(Integer iId, OwnerType eType) {
    this.id= iId;
    this.type = eType;
} 

解析输入文件时,您可以使用valueOf方法将字符串值转换为OwnerType

this.data.add
    (new Owner(Integer.parseInt(owner[0]), OwnerType.valueOf(owner[1])));

答案 1 :(得分:1)

任何Enumeration对象默认都有方法valueOf(String key),这个方法所做的就是在enum类中搜索所有已定义的值,如果找到它则返回正确的值。

了解更多信息请继续关注:

https://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#valueOf%28java.lang.Class,%20java.lang.String%29 enter link description here

在这个特殊情况下,enum;

public enum OwnerType {
    HUMAN,INSTITUTION   
}

如果我们使用OwnerType.valueOf(" HUMAN"),将返回枚举类型HUMAN

这里使用:

try {
    File file = new File("resources/Owner.txt");
    Scanner fileContent = new Scanner(file);
    while (fileContent.hasNextLine()) {
        String[] person = fileContent.nextLine().split(" ");
        this.data.add(new Owner(person[0],OwnerType.valueOf(person[1])));
    }
} catch (FileNotFoundException err){
    System.out.println(err);
}