Java 通过 instanceof 判断对象类型


#Java 反射、泛型与注解#


instanceof 是一个保留关键词,返回 boolen 类型。本质上是一个类似 >== 的操作符。

示例

示例1:

@Test
public void test_instanceof() {
    Long num = 0L;
    boolean result = num instanceof Long;
    System.out.println(result);
	// 以上代码输出: true
}

示例2:

@Test
public void test_instanceof() {
    Long num = 0L;

    System.out.println(num instanceof Long);
    // 以上代码输出: true

    System.out.println(num instanceof Number);
    // 以上代码输出: true

    // System.out.println(num instanceof Integer);
    // 上一行会报编译错误: 错误: 不兼容的类型: Long无法转换为Integer
}

示例3:

@Test
public void test_instanceof() {
    Long num = 0L;
    Object obj = num;

    System.out.println(obj instanceof Long);
    // 以上代码输出: true

    System.out.println(obj instanceof Number);
    // 以上代码输出: true

    System.out.println(obj instanceof Integer);
    // 以上代码输出: false
}

示例4:

@Test
public void test_instanceof() {
    Object obj = Long.class;

    System.out.println(obj instanceof Class);
    // 以上代码输出: true

    System.out.println(obj instanceof Class<?>);
    // 以上代码输出: true

    // System.out.println(obj instanceof Class<? extends Number>);
    // 以上代码会编译错误: 错误: Object 无法安全地转换为 Class<? extends Number>

    System.out.println(obj instanceof Long);
    // 以上代码输出: false

    System.out.println(obj instanceof Number);
    // 以上代码输出: false

    System.out.println(obj instanceof Integer);
    // 以上代码输出: false
}

( 本文完 )