Convert null to Enum.NULL

I have an enum like this:

public enum Type{
    CSV, EXCEL, PDF, URL, NULL
}

now I am reading a line from an xml file and use the Type.valueOf(string);parsing values ​​to parse. if this part does not exist in the xml file, string null, not "null". Is there a way to convert nullto "null"or change return null;to return "null";? or should not even be included in the listing?

+4
source share
2 answers

What you need to do is use something else than NULL, and analyze this case differently:

public enum Type {
  CSV, EXCEL, PDF, URL, NONE;
  public static Type from(String text) {
    if (text == null) {
      return NONE;
    } else {
      return valueOf(text.toUpperCase());
    }
  }
}

Or better yet, use the options:

public enum Type {
  CSV, EXCEL, PDF, URL; // Note the absence of NULL/NONE/WHATEVER
  public static Optional<Type> from(String text) {
    return Optional.ofNullable(text)
      .map(String::toUpperCase)
      .map(Type::valueOf);
  }
}
+5
source

Type.valueOf(null), NullPointerException. :

  • , null:

    public static Type getType(String name) {
        if (name == null)
            return Type.NULL;
        else
            return Type.valueOf(name.toUpperCase());
    }
    
  • ( null) :

    public enum Type {
        CSV, EXCEL, PDF, URL, NULL;
    
        private static final Map<String, Type> TYPE_BY_NAME = new HashMap<>();
        static {
            TYPE_BY_NAME.put(CSV.name(), CSV);
            TYPE_BY_NAME.put(EXCEL.name(), EXCEL);
            TYPE_BY_NAME.put(PDF.name(), PDF);
            TYPE_BY_NAME.put(URL.name(), URL);
            TYPE_BY_NAME.put(null, NULL);
        }
    
        public static Type getType(String name) {
            String s = name == null ? null : name.toUpperCase();
            return TYPE_BY_NAME.get(s);
        }
    

, , . , , .

+4

Source: https://habr.com/ru/post/1678101/


All Articles