Skip to content

Instantly share code, notes, and snippets.

@twiceyuan
Last active December 8, 2016 02:05
Show Gist options
  • Save twiceyuan/a6776ec274cb9e6fa41a0d5ec350fd98 to your computer and use it in GitHub Desktop.
Save twiceyuan/a6776ec274cb9e6fa41a0d5ec350fd98 to your computer and use it in GitHub Desktop.
获得泛型 T.class 的方法。使用该方法时必须使用匿名实现(new 的时候带 {})
public class GenericTypeDemo {
public static void main(String args[]) {
Foo<String> foo = new Foo<String>() { };
// 在类的外部这样获取
Type type = ((ParameterizedType) foo.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
System.out.println(type);
// 在类的内部这样获取
System.out.println(foo.getTClass());
}
static abstract class Foo<T> {
public Class<T> getTClass() {
Class<T> tClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
return tClass;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment