1

I am currently messing around with Java and dynamic return values

@SuppressWarnings("unchecked")
public static <T> T get(String path)
{
    return null;
}

How can i get the Type of T ?

  • There is .getClass() - https://docs.oracle.com/javase/tutorial/reflect/class/classNew.html Or if you need to check if it's instance of another class and get boolean use instanceof. EDIT: didn't see it's not about class of arguments, you can't check T. There is something called erasures and it exists only at compile time, at runtime it's deleted. – whatamidoingwithmylife Dec 06 '17 at 19:03
  • 7
    You can't, that information doesn't exist at runtime. – Mark Rotteveel Dec 06 '17 at 19:04
  • In the scope of the method there's no sense in knowing which type is T, the method should not care about it, that's why the method uses generics. – Marco Avila Dec 06 '17 at 19:05
  • As others mentioned, there is no need to know its type. If you have a generic class and you need to know T's specific type, you are doing something wrong. – BackSlash Dec 06 '17 at 19:08
  • @GCP the unction from the question always returns null, so when `.getClass()` will be called on null object, then NullPointerException will be thrown. – krokodilko Dec 06 '17 at 19:09
  • @krokodilko I thought he was talking about parameter type/class, I edited my original comment. – whatamidoingwithmylife Dec 06 '17 at 19:11

0 Answers0