Thursday, September 3, 2009

Reflecting Darkly on Generics

Although you can do reflection on generic types in Java, the information available from java.lang.Class and the java.lang.reflect classes is pretty raw.

I came across a situation the other day where I had something like:


interface I<T> {
T foo ();
}

abstract class C implements I<String> {
}


and I wanted to ask: what does C.foo() return? The answer, obvious to a human reader, is String, but deducing this using reflection requires traversing C's ancestry and explicitly resolving the type variable T.

It would be nice if there were some general-purpose facilities built into Java to answer questions like:


  • If a given Method m is invoked on an object declared to be of type T, what are the type bounds on the returned value?

  • If a given Method m that takes n arguments is invoked an object declared to be of type T with arguments of specified types Ui, but omitting one argument k, so that 0 ≤ i < k and k < i < n, what are the type bounds on argument k?


Without having made any attempt to write any such facilities myself, I can't say exactly how hard they would be to write, but my feeling is that they would not be easy.

But, if that's not bad enough, they might be impossible to write in a definitive way consistent with the Java language specification—see, for example, this article, which says that the Java generic type inference algorithm is underspecified.

No comments:

Post a Comment