본문 바로가기
Study/Java

[Java] instanceof vs isInstance()

by 검프 2021. 3. 11.

instanceof과 isInstance()모두 객체의 클래스를 확인하는데 사용합니다.

하지만 클래스의 체크 시점이 정적(컴파일 타임)이냐 동적(런타임)이냐의 차이를 보입니다.

즉, instanceof는 컴파일타임에 타입 에러를 체크하고, isInstance()는 런타임에 타입 에러 체크를 합니다.

 

isInstance() 사용 예

// 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 사용 예

public class Test 
{ 
    public static void main(String[] args) 
    { 
        Integer i = new Integer(5); 
        System.out.println(i instanceof String); 
    } 
}

에러가 바로 나타나는 것을 확인할 수 있습니다.

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

 

결론

런타임에서 타입체크가 필요하다면 isInstance() 컴파일시 강력한 타입 체크가 필요하다면 instanceof을 사용하면 될 것 같습니다.

 

또다른 결론,

Class Casting 자체가 안티패턴이라는 말이 있는데요.

타입 캐스팅은 메소드로 들어온 객체에 대한 차별을 일으킨다고 합니다.

즉, 들어온 객체에 대해 어떤 객체인지 묻고 다른 결과를 주는 것과 같다고 합니다. (똑같이 주문한 음식이 사람의 키에 따라 다르게 나온다면, 차별이라 느끼겠죠?)

이는 이후에 다뤄볼 예정입니다.

 

Refer

https://www.yegor256.com/2015/04/02/class-casting-is-anti-pattern.html

https://www.geeksforgeeks.org/instanceof-operator-vs-isinstance-method-in-java/

댓글