IT박스

Java에서 사용되는 'instanceof'연산자는 무엇입니까?

itboxs 2020. 6. 7. 10:54
반응형

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

이게 도움이 되길 바란다!


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


이 연산자를 사용하면 객체 유형을 결정할 수 있습니다. 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

다른 답변에서 언급했듯이 일반적인 표준 사용법은 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

As Test is not a parent class of String. OTOH, this compiles perfectly and prints false as expected:

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 

    }
}

Can be used as a shorthand in equality check.

So this code

if(ob != null && this.getClass() == ob.getClass) {
}

Can be written as

if(ob instanceOf ClassA) {
}

Most people have correctly explained the "What" of this question but no one explained "How" correctly.

So here's a simple illustration:

String s = new String("Hello");
if (s instanceof String) System.out.println("s is instance of String"); // True
if (s instanceof Object) System.out.println("s is instance of Object"); // True
//if (s instanceof StringBuffer) System.out.println("s is instance of StringBuffer"); // Compile error
Object o = (Object)s;
if (o instanceof StringBuffer) System.out.println("o is instance of StringBuffer"); //No error, returns False
else System.out.println("Not an instance of StringBuffer"); // 
if (o instanceof String) System.out.println("o is instance of String"); //True

Outputs:

s is instance of String
s is instance of Object
Not an instance of StringBuffer
o is instance of String

The reason for compiler error when comparing s with StringBuffer is well explained in docs:

You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

which implies the LHS must either be an instance of RHS or of a Class that either implements RHS or extends RHS.

How to use use instanceof then?
Since every Class extends Object, type-casting LHS to object will always work in your favour:

String s = new String("Hello");
if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //No compiler error now :)
else System.out.println("Not an instance of StringBuffer");

Outputs:

Not an instance of StringBuffer

The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html


Instance of keyword is helpful when you want to know particular object's instance .

Suppose you are throw exception and when you have catch then perform sum custom operation and then again continue as per your logic (throws or log etc)

Example : 1) User created custom exception "InvalidExtensionsException" and throw it as per logic

2) Now in catch block catch (Exception e) { perform sum logic if exception type is "InvalidExtensionsException"

InvalidExtensionsException InvalidException =(InvalidExtensionsException)e;

3) If you are not checking instance of and exception type is Null pointer exception your code will break.

So your logic should be inside of instance of if (e instanceof InvalidExtensionsException){ InvalidExtensionsException InvalidException =(InvalidExtensionsException)e; }

Above example is wrong coding practice However this example is help you to understand use of instance of it.


class Test48{
public static void main (String args[]){
Object Obj=new Hello();
//Hello obj=new Hello;
System.out.println(Obj instanceof String);
System.out.println(Obj instanceof Hello);
System.out.println(Obj instanceof Object);
Hello h=null;
System.out.println(h instanceof Hello);
System.out.println(h instanceof Object);
}
}  

Very simple code example:

If (object1 instanceof Class1) {
   // do something
} else if (object1 instanceof Class2) {
   // do something different
}

Be careful here. In the example above, if Class1 is Object, the first comparison will always be true. So, just like with exceptions, hierarchical order matters!


You could use Map to make higher abstraction on instance of

private final Map<Class, Consumer<String>> actions = new HashMap<>();

Then having such map add some action to it:

actions.put(String.class, new Consumer<String>() {
        @Override
        public void accept(String s) {
           System.out.println("action for String");       
        }
    };

Then having an Object of not known type you could get specific action from that map:

actions.get(someObject).accept(someObject)

The instanceof operator is used to check whether the object is an instance of the specified type. (class or subclass or interface).

The instanceof is also known as type comparison operator because it compares the instance with type. It returns either true or false.

class Simple1 {  
public static void main(String args[]) {  
Simple1 s=new Simple1();  
System.out.println(s instanceof Simple1); //true  
}  
}  

If we apply the instanceof operator with any variable that has null value, it returns false.

참고URL : https://stackoverflow.com/questions/7313559/what-is-the-instanceof-operator-used-for-in-java

반응형