Java: Detecting generic type by Enum [duplicate]

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Java: Detecting generic type by Enum [duplicate]



This question already has an answer here:



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:


class


T


Action


Action


ActionType


GET_STRING


ActionType


Action


T


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.


Action


ActionType#getType()


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?


enum


interface



Thanks for your help in advance!!



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





No, not really. That's not a thing you can do with enums.
– Louis Wasserman
Aug 10 at 21:24





maybe with a switch in class action. what is T?
– Ray Tayek
Aug 10 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 <T extends String>), 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 at 21:49






@Alberto My goal it to automatically get an Action<String>, 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 at 8:25




Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard