java中instanceof的基本使用

java中的instanceof运算符是用于判断对象是否是指定类或这个指定类的子类的一个实例,返回值是布尔类型。

语法:

  boolean result = object instanceof class

参数说明:

  result:返回结果值,true或false。true表示object是指定类或指定类子类的一个实例;false不是。

    注:如果object是null,返回false。

  object:必选项,需要判断的对象

  class:必选项,已定义的类

特殊情况:

  在编译状态中,class可以是object对象的父类,自身类,子类。在这三种情况下Java编译时不会报错。

  在运行转态中,class可以是object对象的父类,自身类,不能是子类。在前两种情况下result的结果为true,最后一种为false。但是class为子类时编译不会报错。运行结果为false。

举个栗子:

关闭资源的通用方法:

public static void closeAll(Object... args){
    for(int i = 0; i < args.length; i++){
        //close ResultSet
        if(args[i] instanceof ResultSet){
            closeResultSet((ResultSet)args[i]);
            continue;  
        }  
        //close Statement
        if(args[i] instanceof Statement){
            closeStatement((Statement)args[i]);
            continue;  
        } 
        //close PreparedStatement    
        if(args[i] instanceof PreparedStatement){
            closePreparedStatement((PreparedStatement)args[i]);
            continue;  
        } 
        //close Connection
        if(args[i] instanceof Connection){
            closeConnection((Connection)args[i]);
            continue;  
        } 
    }  
}

  

猜你喜欢

转载自www.cnblogs.com/licheng0201/p/9967791.html