简体   繁体   中英

Cannot Instantiate the type Error in enum

I get an error saying I cannot instantiate type CustomLogLevel for static members.

I looked around and I'm pulling this from an existing project that works so any help what I'm missing here?

public enum CustomLogLevel {
    ERROR(1),
    DEBUG(2),
    INFO(3),
    WARNING(4),
    IGNORE(5);
    private int value;

    static {
        ERROR = new CustomLogLevel("ERROR", 0, 1);
        DEBUG = new CustomLogLevel("DEBUG", 1, 2);
        INFO = new CustomLogLevel("INFO", 2, 3);
        WARNING = new CustomLogLevel("WARNING", 3, 4);
        IGNORE = new CustomLogLevel("IGNORE", 4, 5);
        ENUM$VALUES = new CustomLogLevel[]{ERROR, DEBUG, INFO, WARNING, IGNORE};
    }

    private CustomLogLevel(int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }
}

Enums are static by nature you cannot initiate them.

instead do this :

public enum CustomLogLevel {
    ERROR("ERROR", 1),
    DEBUG("DEBUG", 2),
    INFO("INFO", 3),
    WARNING("WARNING", 4),
    IGNORE("IGNORE", 5);

    private String name;
    private int value;

    private CustomLogLevel(String name, int value) {
        this.name = name;
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }
}

Then you can do this:

CustomLogLevel logLevel = CustomLogLevel.ERROR;

An enum is simply a class with a well-known finite number of instances. These instances are not created manually, but with the special syntax of enums.

Instead of

ENUM_VALUE_1 = new CustomLogLevel(param1, param2);
ENUM_VALUE_2 = new CustomLogLevel(param1, param2);

We simply write at the beginning of the enum body:

ENUM_VALUE_1(param1, param2),
ENUM_VALUE_2(param1, param2);

This syntax is calling the constructor anyway, it's just hidden.

If all you need for each enum value is just the level value, then your constructor needs only one parameter as you wrote, but you don't need the static block (because the first lines already do the job):

public enum CustomLogLevel {
    ERROR(1),
    DEBUG(2),
    INFO(3),
    WARNING(4),
    IGNORE(5);

    private int value;

    private CustomLogLevel(int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }
}

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