实现接受枚举的接口的类

时间:2022-09-02 12:01:42

So, say I have a simple enum and a class that uses it:

所以,假设我有一个简单的枚举和一个使用它的类:

enum ThingType { POTATO, BICYCLE };

class Thing {
    public void setValueType(ThingType value) { ... }
    public ThingType getValueType() { ... }
}

But, in reality, I have lots of different classes that implement setValueType, each with a different kind of enum. I want to make an interface that these classes can implement that supports setValueType and getValueType using generics:

但是,实际上,我有许多不同的类来实现setValueType,每个类都有不同类型的枚举。我想创建一个这样的类可以实现的接口,它使用泛型支持setValueType和getValueType:

interface ValueTypeable {
    public Enum<?> getValueType(); // This works
    public <T extends Enum<T>> setValueType(T value); // this fails horribly
}

I can't change the class model because the classes are auto-generated from an XML schema (JAXB). I feel like I'm not grasping enums and generics combined. The goal here is that I want to be able to allow a user to select from a list of enums (as I already know the type at runtime) and set the value in a particular class.

我无法更改类模型,因为这些类是从XML模式(JAXB)自动生成的。我觉得我没有抓住枚举和泛型相结合。这里的目标是我希望能够允许用户从枚举列表中进行选择(因为我已经知道运行时的类型)并在特定的类中设置值。

Thanks!

2 个解决方案

#1


Have you tried parameterizing the interface itself. Like:

您是否尝试过参数化界面本身。喜欢:

class Thing<E extends Enum<? extends E>> {
  public E getValueType();
  public void setValueType(E value);
}

Then you have the subclass extend the one with right type:

然后你有子类扩展一个正确的类型:

class SomeSubClass implements Thing<ThingType> { ... }

#2


enums are for when you have a fixed set of them. When you say that each implementation has its own, then you no longer have a fixed set, and how you are trying to use enums doesn't match your needs.

枚举是指当你有一组固定的时候。如果您说每个实现都有自己的实现,那么您不再拥有固定的设置,并且您尝试使用枚举的方式与您的需求不符。

You might be interested in the request for Java to be able to have abstract enums.

您可能对Java的请求感兴趣,以便能够使用抽象枚举。

#1


Have you tried parameterizing the interface itself. Like:

您是否尝试过参数化界面本身。喜欢:

class Thing<E extends Enum<? extends E>> {
  public E getValueType();
  public void setValueType(E value);
}

Then you have the subclass extend the one with right type:

然后你有子类扩展一个正确的类型:

class SomeSubClass implements Thing<ThingType> { ... }

#2


enums are for when you have a fixed set of them. When you say that each implementation has its own, then you no longer have a fixed set, and how you are trying to use enums doesn't match your needs.

枚举是指当你有一组固定的时候。如果您说每个实现都有自己的实现,那么您不再拥有固定的设置,并且您尝试使用枚举的方式与您的需求不符。

You might be interested in the request for Java to be able to have abstract enums.

您可能对Java的请求感兴趣,以便能够使用抽象枚举。