1

I have the following class:

Topic.java

public enum Topic {
    CONFIG3("config3"), 
    CONFIG2("config2"),
    CONFIG1("config1")
    ;

    private String name = null;

    Topic(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

When I'm trying to do something like this:

switch (topicName) {
    case Topic.CONFIG2.getName():
        // Do my stuff
        break;
}

The compiler shows an error: "Constant Expression required".

Since the Topic class is already used by many users, I wonder if there is any way to keep it in the same structure but also get the topic value as a constant (in this case - config2).

Any idea?

ernest_k
  • 44,416
  • 5
  • 53
  • 99
TheUnreal
  • 23,434
  • 46
  • 157
  • 277
  • 3
    Create a `Topic` object out of the string and switch over the Enum literals. – Smutje Jan 08 '20 at 12:14
  • Maybe https://stackoverflow.com/questions/3827393/java-switch-statement-constant-expression-required-but-it-is-constant answers it – Reporter Jan 08 '20 at 12:14
  • Did you check this? https://stackoverflow.com/a/4277977/3519504 – Sandeep Kumar Jan 08 '20 at 12:14
  • Does this answer your question? [Java enum : Refactoring switch statements 'constant expression required' compile error?](https://stackoverflow.com/questions/4277819/java-enum-refactoring-switch-statements-constant-expression-required-compile) – Sandeep Kumar Jan 08 '20 at 12:15

0 Answers0