java enum exception

Viewed 127

I have enum class

    package org.testTask.DTO;
    
    public enum Publisher {
        MOSCOW("МОСКВА"),
        ST_PETERSBURG("ПИТЕР"),
        O_REILLY("O’REILLY");
    
        private String name;
    
        private long id;
    
        Publisher(final String name) {
            this.name = name;
            this.id = ordinal();
        }
    
        public String getName() {
            return name;
        }
    
        public long getId() {
            return id;
        }
    }

SQL request

protected Publisher getObject(ResultSet resultSet) throws SQLException {
    return Publisher.valueOf(resultSet.getString("NAME"));
}

and variables in the database with values "МОСКВА", "ПИТЕР", "O’REILLY". But it gives me an error java.lang.IllegalArgumentException: No enum constant org.testTask.DTO.Publisher.ПИТЕР I can't understand what the problem is.

3 Answers

valueOf does not work that way. You have to given it the name of one of the enum members, i.e., valueOf("MOSCOW").

What you call 'name' is not the name of the enum. The name is the thing you can write in source code, Publisher.MOSCOW.

To facilitate lookups by (Russian) name, you need to search through the list of enum members for one with a matching (Russian) name. If you have many more than 3, a map would be useful for efficiency, but I would not bother for a small number of publishers.

.valueOf method returns the enum constant of the specified enumtype with the specified name, means .valueOf("ST_PETERSBURG") not from the field name.

You need to match the name field of enum constants with database value and get the enum

protected Publisher getObject(ResultSet resultSet) throws SQLException {
    String enumName = resultSet.getString("NAME")
    return  Arrays.stream(Publisher.values())
                            .filter(e -> e.getName().equals(enumName))
                            .findFirst().orElse(null);
}

Your Enum members are the names in English, not the ones in Russian. you should pass MOSCOW, ST_PETERSBURG or O_REILLY to valueOf()

Related