如何获取泛型的类型 以及instanceof的简单了解

一、instanceof

a instanceof B:若a是B的一个实例对象,则a instaceof B返回true。所以一直误以为a,必须是由B a=new B()而来。

instanceof在进行强转时可以避免错误。

/**
 * 测试instanceof
 * @author tt
 *
 */
public class Main {
	public static void main(String[] args) {
		Animal animal = get();
		if(animal  instanceof Dog){
			System.out.println("是dog!");
		}
		if(animal instanceof Cat){
			
		}else{
			System.out.println("不是cat!");
		}
	}
	//获得dog实例的一个方法
	public static Animal get(){
		return new Dog();
	}
}
//父类
class Animal{}
//子类1
class Cat extends Animal{}
//子类2
class Dog extends Animal{}

结果:


二、获得泛型的类型

/**
 * 测试泛型
 * @author tt
 *
 */
public class Main {
	public static void main(String[] args) {
		So so=new So();
		Class c = so.getClass();
		//获取c的父类
		Type type = c.getGenericSuperclass();
		/*
		 * 判断type是否属于ParameterizedType的实例
		 * 若是则强转
		 * ParameterizedType可以得到泛型的类型
		 */
		if(type instanceof ParameterizedType){
			ParameterizedType pType=(ParameterizedType)type;
			Type[] types = pType.getActualTypeArguments();
			System.out.println(types[0].getTypeName());
			System.out.println(types[1].getTypeName());
		}
	}
}
class Fa<T1,T2>{}
class So extends Fa<String, Integer>{}

Type是一个接口,其还有子接口,一个实现类Class.



版权声明:本文为NEU_tt原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。