在base類中獲取泛型的型別和泛型物件
阿新 • • 發佈:2019-01-27
class A<T,S> { //獲取S的class public Class<T> poClass = (Class<T>) (((ParameterizedType) this.getClass().getGenericSuperclass())).getActualTypeArguments()[1]; /** * 獲取po物件 * @return */ public T getPo() { T t = null; try { t = poClass.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return t; } } class B extends A<String,Integer> { } public class Generic { public static void main(String[] args) { //輸出class java.lang.Integer System.out.println( new B().poClass); } }