ice world

          There is nothing too difficult if you put your heart into it.
          posts - 104, comments - 103, trackbacks - 0, articles - 0
          這種寫(xiě)法一般都會(huì)在基類中看到,而且是使用了JAVA泛型的,比如我們J2EE中的BaseDAO什么的,請(qǐng)看代碼,其實(shí)簡(jiǎn)寫(xiě)了,分開(kāi)寫(xiě)就明了了。


          基類:
          import java.lang.reflect.ParameterizedType;
          import java.lang.reflect.Type;

          public abstract class SuperClass<T> {

              
          private Class<T> beanClass;

              @SuppressWarnings(
          "unchecked")
              
          public SuperClass() {
                  
          super();
                  ParameterizedType parameterizedType 
          =  (ParameterizedType) getClass().getGenericSuperclass();
                  Type[] types 
          = parameterizedType.getActualTypeArguments();
                  beanClass 
          = (Class<T>) types[0];
              }


              
          public Class<T> getBeanClass() {
                  
          return beanClass;
              }


              
          public void setBeanClass(Class<T> beanClass) {
                  
          this.beanClass = beanClass;
              }

              
              
          public static void main(String[] args) {
                  SuperClass
          <Cat> superClass = new SubClass();
                  System.out.println(superClass.getBeanClass());
              }

              
          }


          子類:
          public class SubClass extends SuperClass<Cat> {
             
             
          public SubClass() {
                 
          super();
              }

             
          }


          class Cat {

             
          public Cat() {
                 
          super();
              }

          }


          運(yùn)行SuperClass后控制臺(tái)會(huì)打印:
          class com.stos.test.generic.Cat

          看到運(yùn)行結(jié)果你可能就清楚了,就是獲取實(shí)際的泛型類。








          Feedback

          # re: (ParameterizedType) getClass().getGenericSuperclass().getActualTypeArguments()[0]得到的是什么?  回復(fù)  更多評(píng)論   

          2015-10-12 17:11 by fsfasf
          傻屌

          # re: (ParameterizedType) getClass().getGenericSuperclass().getActualTypeArguments()[0]得到的是什么?  回復(fù)  更多評(píng)論   

          2015-10-12 17:17 by fsfasf
          你媽靈車(chē)漂移
          主站蜘蛛池模板: 武夷山市| 东乡族自治县| 漳浦县| 四会市| 宁河县| 小金县| 耒阳市| 洞头县| 仲巴县| 农安县| 凌云县| 浦江县| 邻水| 临桂县| 井研县| 安宁市| 双流县| 合川市| 勐海县| 东兰县| 新干县| 涟水县| 时尚| 贵州省| 博白县| 龙岩市| 新营市| 宁明县| 广灵县| 西昌市| 绥滨县| 军事| 富宁县| 土默特左旗| 淮安市| 灌阳县| 东兴市| 商南县| 长顺县| 苍溪县| 雅安市|