Java的泛型反射

來源:互聯網
上載者:User

標籤:color   super   base   nis   system   ase   參數化   type   param   

If the superclass is a parameterized type, the {@code Type}     * object returned must accurately reflect the actual type     * parameters used in the source code. T

上文檔DOC,如果父類是一個參數化型別,那麼Type返回的是參數類型的真實類型

 

package entity;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;/** * Created by Administrator on 2016/11/27 0027. */public class BaseDaoImpl<T> implements BaseDao<T> {    public BaseDaoImpl(){        Type type = getClass().getGenericSuperclass();        Type[] params = ((ParameterizedType)type).getActualTypeArguments();        System.out.println((Class<T>)params[0]);    }    public T findByid(int id) {        return null;    }}
package entity;/** * Created by Administrator on 2016/11/27 0027. */public class UserDaoImpl extends BaseDaoImpl<User> {}
package entity;/** * Created by Administrator on 2016/11/27 0027. */public interface BaseDao<T> {   public T findByid(int id);}
package entity;import org.junit.Test;/** * Created by Administrator on 2016/11/27 0027. */public class GenericTest {    @Test    public void testGeneric(){        UserDaoImpl baseDao = new UserDaoImpl();        //BaseDaoImpl<User> baseDao1 = new BaseDaoImpl<User>();    }}

 

記錄總結,只有繼承的父類為參數化型別,此時反射的

ParameterizedType 才能拿到參數類型

Java的泛型反射

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.