AlessioDP
AlessioDP

Reputation: 88

String enum in Java

I have an enum:

public enum ListEnums {
    TEST("test1"),
    TEST2("test2");
    private final String txt;
    ListEnums(String str){
        txt = str;
    }
    @Override
    public String toString(){return txt;}

I want get the enum string without call .toString().

Like:mymethod(ListEnums.TEST);

No: mymethod(ListEnums.TEST.toString());

Is it possible?

EDIT The string return must be contains special chars.

Upvotes: 0

Views: 98

Answers (2)

Bradley D
Bradley D

Reputation: 2815

It's OK, and a good practice to use getters in your enums. Also good to keep your constructor private (though enums are private by default)....

public enum ListEnums {
    TEST("test1"),
    TEST2("test2");

    private final String txt;

    private ListEnums(String str){
        txt = str;
    }

    public String getTxt() {
        return txt;
    }
}

public static void main(String[] args) {
    System.out.println(ListEnums.TEST.getTxt());
}

Upvotes: 0

here:

public enum ListEnums {
    TEST("test1"),
    TEST2("test2);
    private final String txt;
    ListEnums(String str){
        txt = str;
    }
    @Override
    public String toString(){
        return txt;
    }

if you call ListEnum.TEST.name() you will get TEST which is almost the same as calling toString()... if you instead do ListEnum.TEST then the name will be printed...

so Renaming the Enum constants is the way to go...

and the best part is: you will get rid off the constructor, the toString method and the variable txt...

you just dont need it anymore. :)

Upvotes: 1

Related Questions