获得泛型类的方法

1、泛型类

public class Function {
	private Long id = new Long(0);
	
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}
}

 

2、定义基类,包含泛型类型

public abstract class Father<T> {
	private Class<T> entityClass;
	private T model;
	
	public abstract void say();

	/**
	 * 获取父类的泛型类
	 */
	public Class<T> getEntityClass() {
		Class clazz = getClass(); //得到当前类
		Type genericType = clazz.getGenericSuperclass(); //返回当前类的父类的Type,包含泛型参数信息
		
		if(genericType instanceof ParameterizedType){
			Type[] params = ((ParameterizedType)genericType).getActualTypeArguments(); //得到父类的泛型参数信息
			if(params!=null && params.length>0){
				entityClass = (Class)params[0];
			}
		}
		
		return entityClass;
	}

	public T getModel() {
		Class<T> clazz = getEntityClass();
		if(clazz!=null){
			try{
				model = clazz.newInstance(); //泛型类的实例
			}catch (InstantiationException e){
				e.printStackTrace();
			}catch (IllegalAccessException e){
				e.printStackTrace();
			}
		}
		return model;
	}
}

 

3、继承基类,传入具体的泛型类

public class Son extends Father<Function> {
	@Override
	public void say() {
		String name = null;
		if(getEntityClass()!=null) name = getEntityClass().getName();
		System.out.println(name);
		
		Function func = (Function)getModel();
		if(func!=null){
			System.out.println(func.getId());
		}
	}
	
	public static void main(String[] args) {
		Son fa = new Son();
		fa.say();
	}
}

  

你可能感兴趣的:(泛型类)