How to call Enum individual methods?

后端 未结 2 1656
再見小時候
再見小時候 2021-01-20 02:50

I have an enum that might look like the one below. My goal is to have an enum with some common methods (I enforced this by adding an abstract method) and some \

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-20 02:54

    Why is that?

    The reason is given in the JLS:

    8.9.1. Enum Constants

    ...

    Instance methods declared in enum class bodies may be invoked outside the enclosing enum type only if they override accessible methods in the enclosing enum type (§8.4.8).

    Is there any way to invoke this method? Maybe via reflection?

    Given the above constraint, reflection is the only alternative if you do not want to expose the method in the enclosing enum class. Each enum constant is created as an inner class, like MyEnum$1 and MyEnum$2 in your example. Thus, you can retrieve the Class through the constant's getClass() method and then call your method through reflection (exception handling omitted):

    ...
    Class c = MyEnum.SPECIAL_VALUE.getClass();
    Method m = c.getMethod("sayHello");
    m.invoke(MyEnum.SPECIAL_VALUE);
    ...
    

    I would most likely try to avoid reflection and expose the method in the enum class, and let it throw an UnsupportedOperationException:

    ...
    public void sayHello() {
        throw new UnsupportedOperationException();
    }
    ...
    

    This at least catches unintended calls during runtime - it still does not allow the compiler to catch them during compile time, but neither does the reflection approach.

提交回复
热议问题