1

I have a class with a generic parameter T say Action. Every Action has an ActionType, given in the constructor. For example, it could be GET_STRING. Depending on the ActionType, I would like Java to detect the Action's generic type T.
Example:

public enum ActionType {
    GET_STRING(String.class), GET_BOOLEAN(Boolean.class);

    private ActionType(Class clazz) { this.clazz = clazz}
    private Class clazz;
    Class getType() { return clazz; }
}

Now I want Action to automatically have the type its ActionType#getType() returns.

public class Action<T> {
    public Action(ActionType type) {
        // magic
    }

    public T doAction() { ... }
}

String s = new Action(ActionType.GET_STRING).doAction();

Is that possible? Maybe in a way that the enum implements an interface or something similar?

Thanks for your help in advance!!

Praveen
  • 1,791
  • 3
  • 20
  • 33
Timo Zikeli
  • 166
  • 1
  • 3
  • 7
  • 1
    No, not really. That's not a thing you can do with enums. – Louis Wasserman Aug 10 '18 at 21:24
  • maybe with a switch in class action. what is T? – Ray Tayek Aug 10 '18 at 21:25
  • This is not possible as generic types are resolved at compile-time. This means that when after you compile, T will be erased and (explained simply) you must assume that in runtime all instances of T will behave as if they were of type Object (or String if you declared as ), so there is no actual way to tell at runtime which is the class assigned to T, unless you have an actual object of type T to determine its class using the instanceof operator or reflection utilities. Maybe if you elaborate on what are you trying to accomplish there could be some different approach. – Alberto Hormazabal Aug 10 '18 at 21:49
  • @Alberto My goal it to automatically get an Action, for example, when I construct it like new Action(ActionType.GET_STRING). I don‘t want to cast it, since I just want it to be type-safe. – Timo Zikeli Aug 11 '18 at 08:25

0 Answers0