Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Enum getDeclaringClass vs getClass

Tags:

java

enums

The docs for the Java Enum class state the following about getDeclaringClass:

Returns the Class object corresponding to this enum constant's enum type. Two enum constants e1 and e2 are of the same enum type if and only if e1.getDeclaringClass() == e2.getDeclaringClass(). (The value returned by this method may differ from the one returned by the Object.getClass() method for enum constants with constant-specific class bodies.)

I don't understand when getClass and getDeclaringClass are different. Can someone provide an example along with an explanation?

like image 584
Thomas Eding Avatar asked Apr 22 '11 18:04

Thomas Eding


People also ask

Can enum be comparable?

We can compare enum variables using the following ways. Using Enum. compareTo() method. compareTo() method compares this enum with the specified object for order.

Does enum valueOf throw exception?

The valueOf() enum method converts a specified string to an enum constant value. An exception is thrown if the input string doesn't match an enum value.

How do you find the ordinal value of an enum?

To convert an ordinal into its enum represantation you might want to do this: ReportTypeEnum value = ReportTypeEnum. values()[ordinal];

Can class extends enum in Java?

No, we cannot extend an enum in Java. Java enums can extend java. lang. Enum class implicitly, so enum types cannot extend another class.


1 Answers

Java enum values are permitted to have value-specific class bodies, e.g. (and I hope this syntax is correct...)

public enum MyEnum {     A {        void doSomething() { ... }    },      B {        void doSomethingElse() { ... }    }; } 

This will generate inner classes representing the class bodies for A and B. These inner classes will be subclasses of MyEnum.

MyEnum.A.getClass() will return the anonymous class representing A's class body, which may not be what you want.

MyEnum.A.getDeclaringClass(), on the other hand, will return the Class object representing MyEnum.

For simple enums (i.e. ones without constant-specific class bodies), getClass() and getDeclaringClass() return the same thing.

like image 114
skaffman Avatar answered Sep 23 '22 23:09

skaffman