在Java中,可以使用instanceof
关键字来判断一个对象的类型。
instanceof
关键字用于判断一个对象是否是某个类的实例,或者是否是其子类的实例。语法如下:
对象 instanceof 类名
如果对象是给定类的实例或者子类的实例,则返回true
;否则返回false
。
下面是一个示例:
public class Main { public static void main(String[] args) { Object obj1 = "Hello"; Object obj2 = new Integer(5); if (obj1 instanceof String) { System.out.println("obj1 is a String"); } if (obj2 instanceof Integer) { System.out.println("obj2 is an Integer"); } } }
输出:
obj1 is a String obj2 is an Integer
在上面的示例中,obj1
是一个String
类型的对象,因此obj1 instanceof String
为true
。obj2
是一个Integer
类型的对象,因此obj2 instanceof Integer
为true
。
注意:instanceof
关键字不适用于原始数据类型(如int
、char
等),只能用于对象类型的判断。