简体   繁体   中英

How to set Objects Enum type in constructor?

I have following class:

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?
  } 

}

And

public enum OwnerType {
    HUMAN,INSTITUTION   
}

Which I am calling via:

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

Where Owner.txt has a format of:

ID TYPE

Like that:

1 HUMAN
2 INSTITUTION

My question is:

How can I specify the type property of my Owner Object when I am calling the following?

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

There are two issues here.

First, the Owner 's constructor should receive an OwnerType , not just any Enum :

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

When parsing the input file, you could use the valueOf method to convert a string value to an OwnerType :

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

Any Enumeration object have by default the method valueOf(String key), the what this method does is search into all defined values into your enum class and return the right one if find it.

For more info keep on eye on this:

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

In this particular case the enum;

public enum OwnerType {
    HUMAN,INSTITUTION   
}

if we use OwnerType.valueOf("HUMAN"), will return the enum type HUMAN

Here use this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM