Java中instanceof关键字和isInstance()方法的区别是什么

instanceof关键字和isinstance()方法都用于检查对象的类,那么它们之间有什么区别?下面本篇文章就来带大家了解一下instanceof关键字和isinstance()方法间的区别,希望对大家有所帮助。

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

下面我们通过示例来具体看看instanceof关键字和isinstance()方法间的区别。

使用instanceof关键字来检查对象的类

public class Test 
{ 
    public static void main(String[] args) 
    { 
        Integer i = new Integer(5); 
  
        // 当i是Integer类的实例时,输出true
        System.out.println(i instanceof Integer); 
    } 
}

输出

true

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

public class Test 
{ 
    // 此方法告诉我们对象是否是以字符串“c”形式传递名称类实例。
    public static boolean fun(Object obj, String c) 
                      throws ClassNotFoundException 
    { 
        return Class.forName(c).isinstance(obj); 
    } 
    public static void main(String[] args) 
                      throws ClassNotFoundException 
    { 
        Integer i = new Integer(5); 
  
        // 当i是Integer类的实例时,输出true
        boolean b = fun(i, java.lang.Integer); 
  
        // 因为i不是String类的实例,所以输出false
        boolean b1 = fun(i, java.lang.String); 
  
        //当integer类扩展number类时,如果我也是number类的实例,则输出true。
        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); 
  
        //报错,因为类型不兼容:Integer不能转换为String
        System.out.println(i instanceof String); 
    } 
}

输出

demo.java:10: error: incompatible types: Integer cannot be converted to String
System.out.println(i instanceof String); 
                   ^
1 error

相关视频教程推荐:《Java教程

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...