1. 程式人生 > >Java中的getGenericSuperclass方法的基本用法

Java中的getGenericSuperclass方法的基本用法

通過getGenericSuperclass方法可以獲取當前物件的直接超類的 Type

package cn.tzz.lang.clazz;

public class User {

	private Integer id;
	private String name;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}
public class BaseHibernateDao<T,ID extends Serializable> {
	
	private Class<T> clazz;
	
	public BaseHibernateDao(){
		//當前物件的直接超類的 Type
		Type genericSuperclass = getClass().getGenericSuperclass();
		if(genericSuperclass instanceof ParameterizedType){
			//引數化型別
			ParameterizedType parameterizedType= (ParameterizedType) genericSuperclass;
			//返回表示此型別實際型別引數的 Type 物件的陣列
			Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
			this.clazz= (Class<T>)actualTypeArguments[0];
		}else{
			this.clazz= (Class<T>)genericSuperclass;
		}
	}

	public Class<T> getClazz() {
		return clazz;
	}
}
public class UserService extends BaseHibernateDao<User, Integer>{

}
public class TestUserService {
	public static void main(String[] args) {
		UserService userService = new UserService();
		System.out.println(userService.getClass());
	}
}

執行結果:

class cn.tzz.lang.clazz.User