对abstract关键字的另一番理解

直接上代码:
public abstract class AnnotionMapper<T> implements Comparable<AnnotionMapper<T>>{
	private Type _type;

	public AnnotionMapper() {
		Type superClass = getClass().getGenericSuperclass();// 获取该类的直接超类
		_type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
	}

	
	public Type get_type() {
		return _type;
	}

	public void set_type(Type _type) {
		this._type = _type;
	}

	@Override
	public int compareTo(AnnotionMapper<T> o) {
		return 0;
	}
	public static void main(String[] args) {
		AnnotionMapper<ImageUrl> annotionMapper = new AnnotionMapper<ImageUrl>() {
		};
		//AnnotionMapper<ImageUrl> annotionMapper = new AnnotionMapper<ImageUrl>();
		System.out.println(annotionMapper.get_type());
		/*new TypeReference<T>() {
		};*/
	}

这段代码很奇怪。如果在类上加入abstract关键字也就是main方法中的new就可以获取类上的泛型,如果不加就是注释掉的方法获取泛型就不行。
百思不得其解:后来终于明白了,加了abstract关键字那么new的就是当前类的子类。所以可以获取,如果不加,当前类没有超类直接超类是java.lang.Object.所以不行。

猜你喜欢

转载自chen-sai-201607223902.iteye.com/blog/2364761