0

So, lets say I have an enum, "Data".

public enum Data {

  FIRSTNAME(String.class, "John");

  private final Class<?> defaultClass;
  private final Object defaultData;

  Data(Class<?> clazz, Object data) {
    this.defaultClass = clazz;
    this.defaultData = data;
  }

  public Class<?> getDataClass() {
    return this.defaultClass;
  }
}

Would it be possible to create a method that gets its return type based on the passed Data enum's getDataClass() response? Ie like this:

//This code obviously won't work, it's just another way of showing this.
public [data.getDataClass()] getData(Data data) {
   //Return the data.
}
Knee Snap
  • 91
  • 2
  • Enums and generics mix poorly for a variety of reasons, not the least of which is that Java enum classes are already generic to begin with: the class `enum Data` is equivalent to `class Enum`. There is not an easy typesafe way to do what you want. – scottb Mar 21 '17 at 04:20
  • Darn, that'll be a little annoying. Thanks anyways though. At the least I can verify the object returned is the correct type in the getData method. – Knee Snap Mar 21 '17 at 04:25
  • There was a suggestion in this question to use a class instead as a 'fake enum.' Perhaps that might work? http://stackoverflow.com/questions/11490485/how-to-implement-enum-with-generics – markspace Mar 21 '17 at 04:34
  • 1
    Before there were enums, there were type-safe enumerations. But what the OP wants is twisted - a class (or enum) that's generic over disparate types, different for each constant. This forces the use of a wildcard in `Class>` instead of a generic parameter ``, and that's going to limit what the type token can do for you. – Lew Bloch Mar 21 '17 at 07:58

0 Answers0