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?
We can compare enum variables using the following ways. Using Enum. compareTo() method. compareTo() method compares this enum with the specified object for order.
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.
To convert an ordinal into its enum represantation you might want to do this: ReportTypeEnum value = ReportTypeEnum. values()[ordinal];
No, we cannot extend an enum in Java. Java enums can extend java. lang. Enum class implicitly, so enum types cannot extend another class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With