views:

911

answers:

3

I would like to be able to detirmine the return type of my method call at runtime, but I can not seem to be able to get the Type of T.

    public <T> T getT()
 {
  Object t = null;
  Class<?> c = t.getClass();
  System.out.println(c.getName());
  return (T) t;
 }

Is there any way to determine the Type of T at runtime in Java?

+3  A: 

Your function will throw a NullPointerException, because you call "getClass" on a null pointer (since t is initialized with null). Additionally, generics are used for giving added compile-time type-checking. They do not give you anything special at runtime; generics simply use type Object, but cause the code which uses the generic object to perform implicit casts and also causes the compiler to be aware of how you will use it.

Michael Aaron Safyan
Well this seems to suck.
Milhous
A lot of the 'suckiness' of Java generics happened because the design pragmatically had to be backwards compatible with the JDK 1.4 and earlier libraries.
Stephen C
A: 

If you have a generic Class you can write a constructor that takes the type and saves it into a member of your class. This way you can check the Type during runtime. All information that are only in the generics are gone after compiling.

Janusz
I am working on a database CRUD project, and it has many types, so this solution will not work :-(
Milhous
+1  A: 

Java generics are a static type checking feature. Attempting to retrieve reflection artifacts from generic parameters is typical of poorly thought out design.

In the question example, there is no guarantee that T is a class or even interface. For example

List<? extends Frogs> list = thing.getT();

If you really want to go down this path (and I strongly suggest you don't, not that I expect you to take any notice), then you can supply a reflection object that is statically related to the generic parameter as an argument:

 public <T> T getT(Class<T> clazz) {
     Object value = map.get(clazz);
     return clazz.cast(value);
 }
Tom Hawtin - tackline
In my current Design, I do exactcly that, but I end up having to pass the Class,when I would really like it to know the type given the return type.
Milhous
There isn't necessarily an applicable `Class` object, even if he compile time feature was available at runtime.
Tom Hawtin - tackline