• Tags         
  • 2018-07-30  09:13:21        
  • 68 °C    

    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);
                               ^
     
    转载请保留页面地址:https://www.breakyizhan.com/java/5010.html