Say I have a class like the following
public class AtomEntryHandler implements ConsumingHandler<AtomEntry>
{
...
}
Is it possible to get the class object AtomEntry.class from the class object of AtomEntryHandler.class ?
I didn't think it was possible due to erasure, but a friend said it is.
There is a blog post that goes over it in detail here:
Reflecting Generics
.You can get the generic type for both interfaces and direct subclasses, but only for the concrete implementation. For example, if you have a
List<T>
instance, you have no way of knowing what it's been parameterized to because of type erasure. If the class definition includes parameterized types that are known at compile time (for example,class StringList extends List<String>
) then you can retrieve that information.If you happen to know
ConsumingHandler
is the only interfaceAtomEntryHandler
implements, and you happen to know it takes just one type argument, you can do this:Otherwise, you can poke around in
getGenericInterfaces()
and theiractualTypeArguments
until you find something that looks like what you're looking for.But if you find yourself needing to do this in real code, either something's probably gone badly wrong in your design, or you're writing some mad genius mock object library and you shouldn't need us to answer these questions.
I could not figure a way to determine base type parameter in case of interface implementation (which does not mean there is none). But this is as close as it gets to it.
Result:
class java.lang.Integer