On 02/28/2014 04:56 PM, Jochen Theodorou wrote:
Hi,

we stumbled here about a strange error involving enums generated from our compiler and that did make me see getEnumConstantsShared() in java.lang.Class.

Now the implementation more or less says, that if calling values() fails in any way, return null and ignore the exception. But why is the exception ignored? It could contain valuable information about what did go wrong....

Hi Jochen,

I agree that the exception should be thrown (possibly an unchecked IllegalArgumentException or something like that with the cause from reflective operation). If Class.isEnum() returns true then the class should be considered an enum and if it is not conformant to specification (which may cause one of those exceptions) then this should be reported as exception and not as null return. The getEnumConstantsShared() is also used as implementation for public method:

    /**
     * Returns the elements of this enum class or *null if this**
**     * Class object does not represent an enum type*.
     *
     * @return an array containing the values comprising the enum class
     *     represented by this Class object in the order they're
     *     declared, or null if this Class object does not
     *     represent an enum type
     * @since 1.5
     */
    public T[] getEnumConstants() {
        T[] values = getEnumConstantsShared();
        return (values != null) ? values.clone() : null;
    }


The behaviour of above method is not consistent with:

    /**
* Returns *true if and only if this class was declared as an enum* in the
     * source code.
     *
* @return true if and only if this class was declared as an enum in the
     *     source code
     * @since 1.5
     */
    public boolean isEnum() {
        // An enum must both directly extend java.lang.Enum and have
        // the ENUM bit set; classes for specialized enum constants
        // don't do the former.
        return (this.getModifiers() & ENUM) != 0 &&
        this.getSuperclass() == java.lang.Enum.class;
    }


...which can return true at the same time as getEnumConstants() returns null for the same class...


I don't believe there's any code out there that relies on this faulty behaviour of getEnumConstants() public method. The other use of getEnumConstantsShared() is to support the Enum.valueOf(Class, String) method which already throws IllegalArgumentException if the 1st parameter does not represent an enum class, so there's no compatibility concerns about that use.


What do experts say?


Regards, Peter


In my code for example, something obviously goes wrong... sometimes... depending on moon-phases or something. and I have not the slightest idea what.

bye Jochen



Reply via email to