温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java中instanceof关键字和isInstance()方法的区别有哪些

发布时间:2020-09-09 10:07:47 来源:亿速云 阅读:183 作者:小新 栏目:编程语言

这篇文章主要介绍Java中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中instanceof关键字和isInstance()方法的区别有哪些的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI