简体   繁体   English

Java - 如何创建接受不同枚举的通用抽象方法?

[英]Java - How to create generic abstract method that accepts different enums?

How can I create abstract generic method doSomething() that accepts different enums?如何创建接受不同枚举的抽象泛型方法 doSomething()? Enum1 and Enum2, Enum3 and so on? Enum1和Enum2、Enum3等等?

public abstract class NumerOne {

public abstract void doSomething();

}

public class NumberTwo extends NumberOne {

@Override
public void doSomething (Enum1 enum1) {
 enum1.createSomething();
}

The most appropriate way to accept a handful of Enum types, but not accept any enum ( <T extends Enum<T> ) or (even worse) Object would be to create an interface and have all the enums that you want to accept implement that interface:接受少数 Enum 类型但不接受任何枚举( <T extends Enum<T> )或(甚至更糟) Object的最合适方法是创建一个接口并让您想要接受的所有枚举实现界面:

interface CreatorOfSomething {
    // I have no idea what type should be returned here,
    // as you don't use this value in your example.
    // But I'm pretty sure it can't be void, so I'll go with Integer.
    // You can have this parameterised as <T> at the interface level.
    Integer createSomething();
}

enum Enum1 implements CreatorOfSomething {
    A, B, C;
    @Override
    public Integer createSomething() {
        return ordinal();
    }
}

enum Enum2 implements CreatorOfSomething {
    X { // you can override the method for individual constants
        @Override
        public Integer createSomething() {
            // .....
        }
    },
    Y { ....
}

Then your method would look like:然后你的方法看起来像:

public void doSomething(CreatorOfSomething creator) {
    creator.createSomething();
}

The code you posted does not even compile.您发布的代码甚至无法编译。 Nor could we run it.我们也不能运行它。 Next time please provide an SSCCE in which you address your question.下次请提供一个SSCCE来解决您的问题。

Here's the solution for the problem you have:这是您遇到的问题的解决方案:

abstract class NumberOne {
    public abstract <T extends Enum<T>> void doSomething(T pEnum);
}

enum Enum1 {
    A, B
}
enum Enum2 {
    C, D
}

public class NumberTwo extends NumberOne {

    @Override public <T extends Enum<T>> void doSomething(final T pEnum) {
        System.out.println("Value: " + pEnum);
    }

    public static void main(final String[] args) {
        final NumberTwo n2 = new NumberTwo();
        n2.doSomething(Enum1.A);
        n2.doSomething(Enum2.D);
    }

}

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

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