顺便说一句。来自@Richard Gomes的文章中的示例静态方法getType有两个错误。它应该是这样的:
static public Class<?> getType(final Class<?> klass, final int pos) {
// obtain anonymous, if any, class for 'this' instance
final Type superclass = klass.getGenericSuperclass();
// test if an anonymous class was employed during the call
if (!(superclass instanceof ParameterizedType)) {
throw new RuntimeException("This instance should belong to an anonymous class");
}
// obtain RTTI of all generic parameters
final Type[] types = ((ParameterizedType) superclass).getActualTypeArguments();
// test if enough generic parameters were passed
if (pos >= types.length) {
throw new RuntimeException(String.format("Could not find generic parameter #%d because only %d parameters were passed", pos, types.length));
}
if (!(types[pos] instanceof Class<?>)) {
throw new RuntimeException("Generic type is not a class but declaration definition(all you get is \"[T]\") " + types[pos]);
}
// return the type descriptor of the requested generic parameter
return (Class<?>) types[pos];
}
遗憾的是它仍然不是灵丹妙药,因为它,如果你在代码中明确
getType(new SomeObject<String>(){}.class, 0) // you get String.class
有工作,但如果你把这个东西就像
getType(new SomeObject<T>(){}.class, 0) // you get T as TypeVariable<D> and not actuall class of it
Just name T.
[this one](http://stackoverflow.com/a/1005283/1416458)看起来更优雅 – jpfreire 2013-01-28 03:19:13