简体   繁体   English

覆盖Java枚举中的泛型方法

[英]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. 但是,请注意, T的类型参数a常数不一样T的类型参数b不变等。

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. 此处明确提供类型是完全可选的,因为编译器将根据提供的参数的类型推断结果类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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