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

这个 运算符 接线员和 isInstance() 方法都用于检查对象的类。但主要的区别在于,当我们想要动态检查对象类时,isInstance()方法就可以工作了。我们不可能通过instanceof运算符来实现这一点。

null

isInstance方法等价于instanceof运算符。该方法用于在运行时使用反射创建对象的情况。一般做法是,如果要在运行时检查类型,则使用isInstance方法,否则可以使用instanceof运算符。

运算符和 isInstance()方法都返回布尔值。isInstance()方法是java中类的方法,而instanceof是运算符。

考虑一个例子:

JAVA

// 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

// 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运算符将抛出编译时错误(不兼容的条件操作数类型)。

JAVA

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);
}
}


输出:

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

必须阅读:

本文由 高拉夫·米格拉尼 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享