package com.sinosoft.web.controller.test.instance;
import org.junit.Test;
import org.springframework.security.core.parameters.P;
import javax.swing.plaf.synth.SynthScrollBarUI;
import java.util.ArrayList;
import java.util.List;
public class InstanceOfTest {
/**
* instanceof :
* instanceof严格来说是java中的一个双目运算符 用来测试一个对象是否是一个类的实例
* 用法:boolean result = obj instanceof Class;
* 解释:
* 其中object为一个对象 Class表示一个类或者是一个接口
* 当object为Class的对象 或者是其直接或间接的子类 或者是其他接口的实现类,结果返回的都是true 否则是false
* <p>
* 注意:
* 编译器会检查object是否能转换右边的class类型,如果不能直接转换就会直接报错,如果不能确定类型,则通过编译 具体看运行待定
*/
@Test
public void instanceTest() {
/*
1.object 必须是引用类型,不能是基本类型
int i = 0;
System.out.println( i instanceof Integer);
System.out.println( i instanceof Object);
instacceof 运算符只能用作是对象的判断。以上会报编译错误。
*/
/**
* 2.object 为null
* System.out.println( null instanceof Object); // false
*
* java 分为两种数据类型:
* 基本数据类型:
* byte short int long char double float boolean
* 引用数据类型:
* 类 接口 数组等;
*java中还有一种特殊的null类型 ,该类型没有名字,所以不能声明为null类型的变量或者转换为null类型,null引用是null类型表达式唯一的可能值,
* null引用也可以转换为任意引用类型。null引用可以成为任意引用类型的特殊符号。
* 在javaSe规范,对instanceof运算符的规定就是:如果object为null,那么将返回false。
*/
/**
*
* 3. object为class类的实例对象。
* Integer i = new Integer(1);
* System.out.println(i instanceof Integer);
*
*/
Integer i = new Integer(1);
System.out.println(i instanceof Integer);//true
Integer integer = 1;
System.out.println(integer instanceof Integer);//true
/**
* 4. obj为class接口的实现类
*集合中有个上层接口List 例如arrayList
* public class ArrayList<E> extends AbstractList<E> implements List<E> ,RandomAccess,Cloneable,java.io.Seriralizable
* 我们可以使用instanceof判断,某个对象是否是list接口的实现类,如果是返回true 否则返回false。
*/
ArrayList arrayList = new ArrayList();
System.out.println(arrayList instanceof List);//true
List list = new ArrayList();
System.out.println(list instanceof List);//true
/**
* 5.object为class类的直接或者是间接的子类
* 例如: 我们创建person类和man类
*/
System.out.println("子类和父类");
Person p = new Person();
man man = new man();
System.out.println(man instanceof Person);//true
System.out.println(man instanceof man);//true
//todo 前面说如果不能相互转化 java编译会出错 为什么父类判断是否是子类对象的时候没有报错 为什么?----->
System.out.println(p instanceof man);//fasle
//todo:解释:
//TODO:也就是说有这样的表达式: object instanceof T . instanceof 运算符的object操作数的类型必须是引用类型或者空类型,否则会发生编译出错。
//todo:如果object强制转化为T时发生编译错误,则关系表达式的instanceof同样会产生编译错误。在这样情况下 表达式的实例就会永远为false。
}
public class Person{
}
public class man extends Person{
}
}
instance of 关键字的解释和使用
最新推荐文章于 2026-03-25 08:40:53 发布
本文详细解析了Java中的instanceof运算符,包括其基本用法、对象为null的情况、对象为类实例、对象为接口实现类以及对象为直接或间接子类时的判断规则。同时,通过实例演示了如何在实际编程中正确使用instanceof。

9万+

被折叠的 条评论
为什么被折叠?



