Home > Blockchain >  Best way to fetch an Enum class name itself as String
Best way to fetch an Enum class name itself as String

Time:10-27

I have an enum.

public enum Market { A, B, C; }

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

CodePudding user response:

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();
    }
}
  •  Tags:  
  • java
  • Related