[java] Java에서 사용되는 ‘instanceof’연산자는 무엇입니까?

instanceof운영자 는 무엇을 사용합니까? 나는 물건을 보았다

if (source instanceof Button) {
    //...
} else {
    //...
}

그러나 그 어느 것도 나에게 의미가 없었습니다. 나는 연구를했지만 아무 설명없이 예제 만 생각해 냈습니다.



답변

instanceof키워드는 객체 (인스턴스)가 지정된 유형의 하위 유형 인지 테스트하는 데 사용되는 이진 연산자 입니다.

상상해보십시오.

interface Domestic {}
class Animal {}
class Dog extends Animal implements Domestic {}
class Cat extends Animal implements Domestic {}

으로 만든 dog 객체를 상상해보십시오 Object dog = new Dog().

dog instanceof Domestic // true - Dog implements Domestic
dog instanceof Animal   // true - Dog extends Animal
dog instanceof Dog      // true - Dog is Dog
dog instanceof Object   // true - Object is the parent type of all objects

그러나,와 Object animal = new Animal();,

animal instanceof Dog // false

왜냐하면 “정제 된” Animal의 수퍼 타입 이기 때문 입니다 Dog.

과,

dog instanceof Cat // does not even compile!

Dog하위 유형도 아니고 수퍼 유형도 아니기 때문에 Cat구현하지도 않습니다.

dog위에서 사용 된 변수 는 유형 Object입니다. 이것은 런타임 작업 instanceof임을 보여주고 런타임 에 객체 유형에 따라 다르게 반응 하는 유스 케이스 를 제공합니다 .

참고 사항 : expressionThatIsNull instanceof T모든 유형에 대해 false입니다 T.

행복한 코딩.


답변

표현식의 왼쪽이 인스턴스 인 경우 true를 리턴하는 연산자 입니다. 이 클래스 이름 .

이런 식으로 생각하십시오. 블록의 모든 집들이 같은 청사진으로 지어 졌다고 가정 해 봅시다. 10 개의 주택 (객체), 1 세트의 청사진 (클래스 정의).

instanceof개체 모음이 있고 그 개체가 무엇인지 확실하지 않은 경우 유용한 도구입니다. 폼에 컨트롤 모음이 있다고 가정 해 봅시다. 어떤 확인란이 있는지 확인한 상태를 읽으려고하지만 일반 상태의 객체에 체크 된 상태를 요청할 수는 없습니다. 대신, 각 객체가 확인란인지 확인하고, 그렇다면 객체를 확인란으로 캐스트하고 속성을 확인하십시오.

if (obj instanceof Checkbox)
{
    Checkbox cb = (Checkbox)obj;
    boolean state = cb.getState();
}


답변

이 사이트 에 설명 된대로 :

instanceof객체 특정 형인 경우 작업자는 검사에 사용될 수있다 ..

if (objectReference instanceof type)

간단한 예 :

String s = "Hello World!"
return s instanceof String;
//result --> true

그러나 instanceof널 참조 변수 / 표현식에 적용 하면 false가 리턴됩니다.

String s = null;
return s instanceof String;
//result --> false

서브 클래스는 수퍼 클래스의 ‘유형’이므로이를 사용하여 instanceof이를 확인할 수 있습니다
.

class Parent {
    public Parent() {}
}

class Child extends Parent {
    public Child() {
        super();
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        System.out.println( child instanceof Parent );
    }
}
//result --> true

이게 도움이 되길 바란다!


답변

이 연산자를 사용하면 객체 유형을 결정할 수 있습니다. 그것은boolean값을 합니다.

예를 들어

package test;

import java.util.Date;
import java.util.Map;
import java.util.HashMap;

public class instanceoftest
{
    public static void main(String args[])
    {
        Map m=new HashMap();
        System.out.println("Returns a boolean value "+(m instanceof Map));
        System.out.println("Returns a boolean value "+(m instanceof HashMap));
        System.out.println("Returns a boolean value "+(m instanceof Object));
        System.out.println("Returns a boolean value "+(m instanceof Date));
    }
} 

출력은 다음과 같습니다

Returns a boolean value true
Returns a boolean value true
Returns a boolean value true
Returns a boolean value false


답변

경우 source이다 object변수 instanceof가있는 있는지 확인하는 방법입니다 Button여부.


답변

다른 답변에서 언급했듯이 일반적인 표준 사용법은 instanceof식별자가보다 구체적인 유형을 참조하는지 확인하는 것입니다. 예:

Object someobject = ... some code which gets something that might be a button ...
if (someobject instanceof Button) {
    // then if someobject is in fact a button this block gets executed
} else {
    // otherwise execute this block
}

그러나 왼쪽 표현식의 유형 은 오른쪽 표현식 의 상위 유형이어야합니다 ( JLS 15.20.2Java Puzzlers, # 50, pp114 참조 ). 예를 들어 다음은 컴파일에 실패합니다.

public class Test {
    public static void main(String [] args) {
        System.out.println(new Test() instanceof String); // will fail to compile
    }
}

이 메시지와 함께 컴파일에 실패합니다 :

Test.java:6: error: inconvertible types
        System.out.println(t instanceof String);
                       ^
  required: String
  found:    Test
1 error

으로는 Test의 부모 클래스되지 않습니다 String. OTOH, 이것은 완벽하게 컴파일 false되고 예상대로 인쇄 됩니다.

public class Test {
    public static void main(String [] args) {
        Object t = new Test();
        // compiles fine since Object is a parent class to String
        System.out.println(t instanceof String);
    }
}


답변

public class Animal{ float age; }

public class Lion extends Animal { int claws;}

public class Jungle {
    public static void main(String args[]) {

        Animal animal = new Animal();
        Animal animal2 = new Lion();
        Lion lion = new Lion();
        Animal animal3 = new Animal();
        Lion lion2 = new Animal();   //won't compile (can't reference super class object with sub class reference variable) 

        if(animal instanceof Lion)  //false

        if(animal2 instanceof Lion)  //true

        if(lion insanceof Lion) //true

        if(animal3 instanceof Animal) //true 

    }
}