You cannot do it this way, but I would do it like this:
interface HasId() { public int getId(); } public class MyRegistry { private static Map<Class<?>, Map<Integer, Object>> REGISTRY = new HashMap<>(); public static <T extends HasId> T fromInt(int id, Class<T> clazz) { return clazz.cast(REGISTRY.getOrDefault(clazz, Collections.emptyMap()).get(id)); } public static void register(HasId obj) { REGISTRY.putIfAbsent(obj.getClass(), new HashMap<>()).put(obj.getId, obj); } } enum Foo implements HasId { A(15), B(42), C(86), D(99); private final int id; Foo(int id) { this.id = id; MyRegistry.register(this); } public int getId() { return id; } }
Then to use:
Foo foo = MyRegistry.fromInt(15, Foo.class);
Disclaimer: the code cannot compile or work because it was downloaded on my phone (but there is a reasonable chance that it will work)
source share