getGenericSuperclass()和getActualTypeArguments()[0]是什么?

今天学习的时候,看到BaseDao有这样的代码:

protected GenericDAO(T) {
	type = getClass().getGenericSuperclass();	
	Type trueType = ((ParameterizedType) type).getActualTypeArguments()[0];
	this.entityClass = (Class) trueType;
	}

总的来说,
1、getClass()就是获得当前类,getGenericSuperclass()就是获得父类的Type。(而且是带真实参数的!)什么叫真实参数,就是子类引用的泛型类型,而不是父类所标示的。(如果仅仅想获得父类Type,可以用getSuperclass())
2、ParameterizedType是Type类的一个子接口,用来表示参数,getActualTypeArguments()[0]就是获取第1个参数,和Type一样底层都是String,我们可以用getTypeName()来获取它所取到的值。
如果还不明白,我写了一段测试来说明:
首先这是父类:

public class GenericDAO {
	private Class entityClass;
	private Type type;
	
	protected GenericDAO() {
	type = getClass().getGenericSuperclass();	
	Type trueType = ((ParameterizedType) type).getActualTypeArguments()[0];
	this.entityClass = (Class) trueType;
	}
	
	
	public Class getEntityClass() {
		return entityClass;
	}
	public Type getType() {
		return type;
	}
}

这是子类:

public class OptionManager extends GenericDAO {	
	
	public void Test() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		  //先看看type是什么
		  Type type = super.getType();
		  System.out.println(type.getTypeName());
		    
		  Class clazz = super.getEntityClass();
		  Constructor cons = clazz.getDeclaredConstructor((Class[])null);
		  User user = (User)cons.newInstance();
		  user.setUser_name("xiaohong");
		  //看看能否打印出来xiaohong
		  System.out.println(user.getUser_name());
	}
	public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
	OptionManager oManager = new OptionManager();
	oManager.Test();	
	}
}

这是User类:

public class User{
	private String user_name;
	private String user_password;
	public String getUser_name() {
		return user_name;
	}
	public void setUser_name(String user_name) {
		this.user_name = user_name;
	}
	public String getUser_password() {
		return user_password;
	}
	public void setUser_password(String user_password) {
		this.user_password = user_password;
	}
}

打印结果:
getGenericSuperclass()和getActualTypeArguments()[0]是什么?_第1张图片
如果把父类中的[0]换成[1],就会报错:
在这里插入图片描述

你可能感兴趣的:(getGenericSuperclass()和getActualTypeArguments()[0]是什么?)