Last active
December 8, 2016 02:05
-
-
Save twiceyuan/a6776ec274cb9e6fa41a0d5ec350fd98 to your computer and use it in GitHub Desktop.
获得泛型 T.class 的方法。使用该方法时必须使用匿名实现(new 的时候带 {})
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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