0

How can I resolve this method's generic type at runtime?

My method signature: static <T> T get(String key)

The method must remain static.

Jire
  • 9,680
  • 14
  • 52
  • 87
  • post whole code block here for get help – codeaholicguy Nov 17 '15 at 03:23
  • 1
    This code is equivalent to just returning `Object`, the generics really do nothing here. I'd ask why you want to do this, what's the goal? – markspace Nov 17 '15 at 03:26
  • @markspace the point is to use it as a boilerplate-free preferences or attributes system, where I can for example have an inferred type of boolean in such a case: `if (Prefs.get("isActive"))` or for example `int saveTime = Prefs.get("saveTime");` – Jire Nov 17 '15 at 03:28
  • 1
    The goal is to eliminate the need for a `getOrDefault` method and instead calculate the default value for `T` without needing a direct argument of `T`. – Jonathan Beaudoin Nov 17 '15 at 03:30
  • Java can't resolve methods based on return type. It uses parameter types and method names only, so I don't think what you are envisioning is going to work. – markspace Nov 17 '15 at 03:38
  • Generics are a compile-time illusion there to help enforce stronger type-safety and prevent the need for explicit casts. There is no way to resolve a generic type at runtime as far as I know, seeing how they don't even exist in bytecode – Vince Nov 17 '15 at 03:51

1 Answers1

-3

Like this: (Hibernate code)

public class XXXDao<T> {

    private Class<T> entityClass;

    private Class<T> getEntityClass() {
        if (entityClass == null) {
            entityClass = (Class<T>) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
        }
        return entityClass;
    }
    ...
}
Liu guanghua
  • 981
  • 1
  • 9
  • 18
  • This example resolves the generic type of a class and does not work due to `java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType` – Jire Nov 17 '15 at 03:45
  • 1
    Anyway, static T get(String key) method cannot determine the T class type. If you want, you must add a input parameter, like this: static T get(Class clazz, String key) – Liu guanghua Nov 17 '15 at 04:12