简体   繁体   中英

Override generic method in Java enum

In order to offer specific behavior to each instance of an enum for a common public method we could do the following:

public enum Action { 
    a{
        void doAction(...){
            // some code
        }

    }, 
    b{
        void doAction(...){
            // some code
        }

    }, 
    c{
        void doAction(...){
            // some code
        }

    };

    abstract void doAction (...);
}

Is there any way of giving specific implementation to an abstract generic method defined in an enum?

Eg:

abstract<T> T doAction (T t);

I read in other questions that it shouldn't be possible, but I've been struggling for workarounds and came up with overly complicated contraptions. Maybe generics aren't the right way. Is there an easier way to achieve this?

Yes, you can do it. Just leave the abstract method definition as it is and in each of the enum constants, you have to do something like:

a{
    @Override
    <T> T doAction(T t) {
        //your implementation
    }
}...

However, please note that the T type-parameter in the a constant is not the same as the T type parameter for the b constant and so on.

When done, you can use it like this:

String string = Action.a.<String>doAction("hello");

or

Integer integer = Action.b.<Integer>doAction(1);

Explicitly providing the type here is completely optional, as the compiler will infer the resulting type by the type of the provided argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM