0

I am trying to use an enum as a map to retrieve country names from alpha-2 country codes. I have an enum class like so:

public enum Country {
    AF("Afghanistan");

    @Getter
    private final String fullName;

    private Country(String fullName) {
      this.fullName = fullName;
    }

}

I would expect that if I instantiated a new Country object like so

String country = new Country("AF").getFullName();

The variable country should be set to "Afghanistan", but I am getting an error that the object cannot be Country cannot be instantiated.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Evan Gertis
  • 1,796
  • 2
  • 25
  • 59
  • try `AF.getFullName()` ;) (enum constructors must all be invoked within the enum... ...without "new" keyword!; ... so `AF("Afghanistan")` is the enum(instance) declaration + constructor invocation) – xerx593 Apr 22 '20 at 18:00
  • problem is I would ideally like to use a variable in place of the hardcoded string `String country = new Country(countryCode).getFullName();`. – Evan Gertis Apr 22 '20 at 18:02
  • Either use `Country.AF`, or `Country.valueOf("AF")`. Also, this has nothing to do with Lombok, you only use that to generate a getter. – Mark Rotteveel Apr 22 '20 at 18:06
  • if you want the `AF` Country from the String `"AF"`, you can use: `Country.valueOf("AF")` ..if you need this functionality for full name, you'd have to implement. – xerx593 Apr 22 '20 at 18:08

3 Answers3

1

check this https://stackoverflow.com/a/16851422/3874879 Enums cannot be instantiated, they are like a constant, you must define them at compile time, I guess

1

An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).

You can access enum constants with the dot syntax:

String country = Country.AF.getFullName();

Enum constants are public, static and final. You cannot create enum instances using new.

Enum constants (AF in your case) are the only instances you can use.

ikos23
  • 4,879
  • 10
  • 41
  • 60
0

You cannot create an object.

Check this documentation: https://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html

And try this: String country = Country.AF.getFullName();

EDIT: If you want to use a variable in place of the hardcoded string you can define some method like findByCountryCode(countryCode) in your enum

public Country findByCountryCode(String code) {
    for (Country value : Country.values()) {
        if (value.getFullName().equals(code)) {
            return value;
        }
    }
    return null;
}
a.eugene
  • 104
  • 4