2

I have an enum.

public enum Market { A, B, C; }

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

0

2 Answers 2

6

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();
    }
}
Sign up to request clarification or add additional context in comments.

8 Comments

Or call getClass().getSimpleName() on any of the enum's values.
@StephenC Sure, that works, too. But the class name is not dependent on the enum value.
@chrylis-cautiouslyoptimistic- I think it depends if you subclass them (e.g. A {...}).
@StephenC You can specify a body on the constant, and it acts as anonymous subclass: ideone.com/XRA5uO
@StephenC I knew I've gone jd-diving and seen more dollar signs than a cable-TV bill.
|
1

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();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.