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();
    }
}
8
  • 3
    Or call getClass().getSimpleName() on any of the enum's values.
    – Stephen C
    Oct 27, 2021 at 2:28
  • @StephenC Sure, that works, too. But the class name is not dependent on the enum value. Oct 27, 2021 at 2:32
  • 4
    @chrylis-cautiouslyoptimistic- I think it depends if you subclass them (e.g. A {...}).
    – shmosel
    Oct 27, 2021 at 2:42
  • 1
    @StephenC You can specify a body on the constant, and it acts as anonymous subclass: ideone.com/XRA5uO
    – shmosel
    Oct 27, 2021 at 2:58
  • 2
    @StephenC I knew I've gone jd-diving and seen more dollar signs than a cable-TV bill. Oct 27, 2021 at 3:10
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();
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.