adimoh
adimoh

Reputation: 728

Best way to fetch an Enum class name itself as String

I have an enum.

public enum Market { A, B, C; }

I want to get the class name. So getEnumClassName() returns the String "Market".

Upvotes: 2

Views: 1455

Answers (2)

DuncG
DuncG

Reputation: 15116

Enum values have getDeclaringClass method which returns consistent value of the declaring class, even if the enum values themselves are anonymous classes and may have different values of getClass().getSimpleName().

So a declaration of getEnumClassName() does not need to include Market and you could cut/paste this method to different enum classes as is:

public enum Market {
    A,
    B,
    C;
    public static String getEnumClassName() {
        return values()[0].getDeclaringClass().getSimpleName();
    }
}

Upvotes: 1

Charlie Armstrong
Charlie Armstrong

Reputation: 2342

All Java classes have the getSimpleName() method, which returns the name of the class, or enum, whichever it may be. So to get the name of the Market enum as a string you could use:

Market.class.getSimpleName()

Or, if you want Market to have a method getEnumClassName() that returns the name as you describe, you could write it like so:

public enum Market {
    A,
    B,
    C;

    public static String getEnumClassName() {
        return Market.class.getSimpleName();
    }
}

Upvotes: 6

Related Questions