Java中的instanceof运算符与isInstance()方法

作者: Arvin Chen 分类: Java 来源: Break易站(www.breakyizhan.com)

instanceof运算符和isInstance()方法都用于检查对象的类。但是当我们想要动态检查对象类时,主要区别就出现了。在这种情况下,isInstance()方法将起作用。我们无法通过instanceof运算符来实现这一点。

Java中的instanceof运算符与isInstance()方法的实例

instanceof运算符和isInstance()方法都返回一个布尔值。考虑一个例子:

// Java program to demonstrate working of
// instanceof operator
public class Test
{
    public static void main(String[] args)
    {
        Integer i = new Integer(5);

        // prints true as i is instance of class
        // Integer
        System.out.println(i instanceof Integer);
    }
}

输出:

true

现在,如果我们想在运行时检查对象的类,那么我们必须使用isInstance()方法。

// Java program to demonstrate working of isInstance()
// method
public class Test
{
    // This method tells us whether the object is an
    // instance of class whose name is passed as a
    // string 'c'.
    public static boolean fun(Object obj, String c)
                      throws ClassNotFoundException
    {
        return Class.forName(c).isInstance(obj);
    }

    // Driver code that calls fun()
    public static void main(String[] args)
                      throws ClassNotFoundException
    {
        Integer i = new Integer(5);

        // print true as i is instance of class
        // Integer
        boolean b = fun(i, "java.lang.Integer");

        // print false as i is not instance of class
        // String
        boolean b1 = fun(i, "java.lang.String");

        /* print true as i is also instance of class
           Number as Integer class extends Number
           class*/
        boolean b2 = fun(i, "java.lang.Number");

        System.out.println(b);
        System.out.println(b1);
        System.out.println(b2);
    }
}

输出:

true
false
true

注意:如果我们检查对象与其未实例化的其他类,则instanceof运算符会抛出编译时错误(不兼容的条件操作数类型)。

public class Test
{
    public static void main(String[] args)
    {
        Integer i = new Integer(5);

        // Below line causes compile time error:-
        // Incompatible conditional operand types
        // Integer and String
        System.out.println(i instanceof String);
    }
}

输出:

13: error: incompatible types: Integer cannot be converted to String
        System.out.println(i instanceof String);
                           ^
  •   本文标题:Java中的instanceof运算符与isInstance()方法 - Break易站
    转载请保留页面地址:https://www.breakyizhan.com/java/5010.html
    扫描二维码添加微信 
  • ,领取淘宝优惠券,淘宝购物更优惠。现在添加微信,还可以领取机械键盘优惠券!添加微信后,分享淘宝选中的机械键盘给淘宝机器人即可领取!
    支持我们,就用微信淘宝!

    发表笔记

    电子邮件地址不会被公开。 必填项已用*标注

    更多阅读