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 才能拿到参数类型
时间: 2024-10-29 19:06:03