使用“instanceof”;在Java中

什么是'用于?

我了解到Java有instanceof操作符。你能详细说明它在哪里使用,它的优点是什么吗?

911657 次浏览

运算符是一个关键字,可用于测试对象是否为指定类型。

例子:

public class MainClass {
public static void main(String[] a) {


String s = "Hello";
int i = 0;
String g;
if (s instanceof java.lang.String) {
// This is going to be printed
System.out.println("s is a String");
}
if (i instanceof Integer) {
// This is going to be printed as autoboxing will happen (int -> Integer)
System.out.println("i is an Integer");
}
if (g instanceof java.lang.String) {
// This case is not going to happen because g is not initialized and
// therefore is null and instanceof returns false for null.
System.out.println("g is a String");
}
}

这是我的

instanceof用于检查对象是否是类的实例、子类的实例或实现特定接口的类的实例。

在这里阅读更多Oracle语言定义

基本上,你检查一个对象是否是一个特定类的实例。 当你有一个超类或接口类型的对象的引用或参数,并且需要知道实际对象是否有其他类型(通常是更具体的类型)时,通常会使用它

例子:

public void doSomething(Number param) {
if( param instanceof Double) {
System.out.println("param is a Double");
}
else if( param instanceof Integer) {
System.out.println("param is an Integer");
}


if( param instanceof Comparable) {
//subclasses of Number like Double etc. implement Comparable
//other subclasses might not -> you could pass Number instances that don't implement that interface
System.out.println("param is comparable");
}
}

请注意,如果您必须经常使用该操作符,则通常暗示您的设计存在一些缺陷。因此,在一个设计良好的应用程序中,您应该尽可能少地使用该操作符(当然,这个一般规则也有例外)。

instanceof可用于确定对象的实际类型:

class A { }
class C extends A { }
class D extends A { }


public static void testInstance(){
A c = new C();
A d = new D();
Assert.assertTrue(c instanceof A && d instanceof A);
Assert.assertTrue(c instanceof C && d instanceof D);
Assert.assertFalse(c instanceof D);
Assert.assertFalse(d instanceof C);
}