泛型真實類型
阿新 • • 發佈:2017-05-18
rate 表示 泛型 port const lang pack children str
把項目中的代碼抽出父類,有時需要用泛型。如果此時涉及到hibernate等數據庫操作,比如"select u from User u",那麽User怎麽怎麽表示出來呢?以下是研究的代碼:
父類:
import static org.junit.Assert.*; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import org.junit.Test; public class Father<T> { public Father() { // TODO Auto-generated constructor stub System.out.println(this.getClass());//class mypss.children System.out.println(this.getClass().getSuperclass());//mypss.Father System.out.println(this.getClass().getGenericSuperclass());//mypss.Father<java.lang.Long> 帶上了泛型 ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass(); Type[] actualTypes = parameterizedType.getActualTypeArguments(); System.out.println(actualTypes[0]);//class java.lang.Long 真實的泛型類型,Long Class<T> actualType = (Class<T>) actualTypes[0]; System.out.println(actualType); } }
子類:
package mypss; import static org.junit.Assert.*; import org.junit.Test; public class children extends Father<Long> { @Test public void testde() throws Exception { System.out.println("子類"); } }
泛型真實類型