如何获取泛型的类型 以及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.


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值