views:

274

answers:

2

That would allow the invoke method to have the right return type. For instance:

class Method<T> {
    T invoke(Object obj, Object... args);
}
+1  A: 

In Java, Generics are only available at compile time. You cannot determine the Generic type at runtime. This allowed the generics implementation to be backwards compatible with old versions of the JVM.

Since generics are only available at compile time, if you know the type of your class then you do not need to use reflection.

Chris Dail
I was going to answer something similar, so instead I'll add here: The Java compiler erases type information on generics at compilation. Since reflection is evaluated at runtime, all the type information will have been already erased, thus making it mostly pointless.
Pesto
This is not true. See http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/TypeLiteral.html
robson
Pesto: It doesn't erase the erased return type of the method!
Tom Hawtin - tackline
A: 

It would have been not unreasonable to make Method generic on erased return type. However, it would be a lot of effort with little gain. The nature of reflection is that you don't know the types at compile-time - otherwise you could statically link.

I guess you could in some case even add new APIs so that the generic type is returned. The information is still on the method, although not from the instance that you pass to it.

Tom Hawtin - tackline