How to call Enum individual methods?

后端 未结 2 1619
再見小時候
再見小時候 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.

    0 讨论(0)
  • 2021-01-20 03:19

    Because SPECIAL_VALUE is an instance of enum and enum has only method syso().you are calling

    Here is the same thing with classes:

    interface Foo {
    
            Foo inst1 = new Foo() {
                @Override
                public void doFoo() {
                }
    
                public void doAnonymous() {
    
                }
            };
            void doFoo();
        }
    

    You cannot call method doAnonymous() like Foo.inst1.doAnonymous() and you are able to access the doAnonymous only via reflection

    0 讨论(0)
提交回复
热议问题