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.

6
  • post whole code block here for get help Commented Nov 17, 2015 at 3: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? Commented Nov 17, 2015 at 3: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"); Commented Nov 17, 2015 at 3: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. Commented Nov 17, 2015 at 3: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. Commented Nov 17, 2015 at 3:38

1 Answer 1

-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;
    }
    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

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
Anyway, static <T> T get(String key) method cannot determine the T class type. If you want, you must add a input parameter, like this: static <T> T get(Class<T> clazz, String key)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.