views:

244

answers:

2

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:

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.

Thanks!

A: 

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.

Stephen Denne
Well, each class has one enum that pairs with it - definitely a set of fixed values. What I want is an interface that these enum-holding classes can implement so I can identify them programmatically and call them from the interface. The alternative is testing each individual containing class type, which becomes a maintainability nightmare.
lucasmo
+3  A: 

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> { ... }
notnoop
There's probably no need to worry about the `Enum` in the bound.
Tom Hawtin - tackline
That definitely works, but the code generator for jaxb interfaces doesn't support genericized interfaces. That might not be so hard to fix, though.
lucasmo