58

instanceof可用于测试对象是给定类的直接实例还是下降实例。instanceof即使接口不能像类一样实例化,也可以与接口一起使用。谁能解释一下如何instanceof工作?

4

8 回答 8

64

首先,我们可以像这样存储instances实现特定interfaceinterface reference variable类。

package com.test;

public class Test implements Testable {

    public static void main(String[] args) {

        Testable testable = new Test();

        // OR

        Test test = new Test();

        if (testeable instanceof Testable)
            System.out.println("instanceof succeeded");
        if (test instanceof Testable)
            System.out.println("instanceof succeeded");
    }
}

interface Testable {

}

即,任何实现特定接口的运行时实例都将通过instanceof测试

编辑

和输出

instanceof succeeded
instanceof succeeded

@RohitJain

您可以使用像这样的匿名内部类来创建接口实例

Runnable runnable = new Runnable() {
    
    public void run() {
        System.out.println("inside run");
    }
};

并且您测试实例是接口类型,使用instanceof这样的运算符

System.out.println(runnable instanceof Runnable);

结果是“真”

于 2012-11-21T06:51:28.287 回答
20

object instanceof object_interface将产生true

于 2012-11-21T06:47:31.107 回答
6

instanceof对 areference进行instance检查,它会检查该instance特定reference对象指向的类型。

现在,由于您可以创建一个 的引用interface,它指向一个实现的实例(与指向 的class概念相同)。因此,您可以对其进行检查。Super class referencesubclass instanceinstanceof

例如:-

public interface MyInterface {
}

class ImplClass implements MyInterface {

    public static void main(String[] args) {
        MyInterface obj = new ImplClass();

        System.out.println(obj instanceof ImplClass);   // Will print true.
    }
}
于 2012-11-21T06:48:05.147 回答
3

-首先instanceof用于比较持有对象的对象引用变量是否属于某种类型。

例如:

public void getObj(Animal a){       // a is an Object Reference Variable of type Animal

    if(a instanceof Dog){


       }

}

-在 的情况下interface,它可以与class哪个实现instanceof一起使用。

例如:

public interface Brush{

  public void paint();
}

public class Strokes implements Brush{

       public void paint(){

          System.out.println("I am painting");

    }


}

public class Test{


  public static void main(String[] args){

          Brush b = new Strokes();

         if(b instanceof Strokes){


           b.paint();
       }
  }

}
于 2012-11-21T06:57:03.190 回答
3
public class Programmers {

    public static boolean hasReallife(Programmer programmer) {
        return programmer instanceof Reallife; ══════════════════╗
    }                                                            ║
                                                                 ║
}                                                                ║
                                                                 ▼
public class ReallifeProgrammer extends Programmer implements Reallife {

    public ReallifeProgrammer() {
        diseases.get("Obesity").heal();
        diseases.get("Perfectionism").heal();
        diseases.get("Agoraphobia").heal();
    }

    @Override
    public void goOut() {
        house.getPC().shutDown();
        wife.argue();
    }

    @Override
    public void doSports() {
        goOut();
        BigWideWorld.getGym("McFit").visit();
    }

    @Override
    public void meetFriends() {
        goOut();
        BigWideWorld.searchFriend().meet();
    }

}
于 2017-03-10T19:32:39.460 回答
2

您好下面将为instanceOf产生True:

•   If S is an ordinary (nonarray) class, then:
    •   If T is a class type, then S must be the same class as T, or S must be a subclass of T;
    •   If T is an interface type, then S must implement interface T.
•   If S is an interface type, then:
    •   If T is a class type, then T must be Object.
    •   If T is an interface type, then T must be the same interface as S or a superinterface of S.
•   If S is a class representing the array type SC[], that is, an array of components of type SC, then:
    •   If T is a class type, then T must be Object.
    •   If T is an interface type, then T must be one of the interfaces implemented by arrays (JLS §4.10.3).
•   If T is an array type TC[], that is, an array of components of type TC, then one of the following must be true:
         - TC and SC are the same primitive type. 
         - TC and SC are reference types, and type SC can be cast to TC by these run-time rules

请转到此链接以获得清晰的想法:

http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.instanceof

于 2016-12-15T07:08:31.530 回答
0

我知道这是一个非常古老的问题,有很多很好的答案。我只想指出理解这个运算符的最简单(至少对我来说最简单)的方法。

如果o instanceof t返回true,则 t castedObj = (t) o;不会抛出ClassCastExceptioncastedObj也不会null

如果您想castedObj稍后访问字段或方法,这很重要/有用 - 您知道通过instanceof检查,以后您将永远不会遇到问题。

唯一的缺点是这可以用于没有泛型的类型。

于 2017-08-14T05:57:48.557 回答
-1

instanceof 运算符将告诉您第一个参数是否是实现第二个参数的对象。不明白为什么不能直接实例化接口很重要。

Integer num = 1;
if (num instanceof Number) {
  System.out.println("An integer is a number!");
}

这就是你所需要的。

于 2012-11-21T06:47:43.573 回答