logo

Java의 instanceof 연산자와 isInstance() 메소드 비교

그만큼 인스턴스 운영자와 isInstance() 두 메소드 모두 객체의 클래스를 확인하는 데 사용됩니다. 그러나 가장 큰 차이점은 객체의 클래스를 동적으로 확인하려는 경우 isInstance() 메서드가 작동한다는 것입니다. instanceof 연산자로는 이 작업을 수행할 수 없습니다.

isInstance 메소드는 instanceof 연산자와 동일합니다. 이 메소드는 리플렉션을 사용하여 런타임에 객체가 생성되는 경우에 사용됩니다. 일반적인 관행에 따르면 런타임에 유형을 확인하려면 isInstance 메서드를 사용하고 그렇지 않으면 instanceof 연산자를 사용할 수 있습니다.



인스턴스 오브 연산자와 isInstance() 메서드는 모두 부울 값을 반환합니다. isInstance() 메소드는 Java에서 Class 클래스의 메소드이고, instanceof는 연산자입니다. 

예를 고려해보세요:

Java
// Java program to demonstrate working of // instanceof operator public class Test {  public static void main(String[] args)  {  Integer i = new Integer(5);  // prints true as i is instance of class  // Integer  System.out.println(i instanceof Integer);  } } 

산출: 



true

이제 런타임에 객체의 클래스를 확인하려면 다음을 사용해야 합니다. isInstance() 방법.

Java
// 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

메모: 인스턴스화하지 않은 다른 클래스로 객체를 검사하면 인스턴스오브 연산자가 컴파일 시간 오류(호환되지 않는 조건부 피연산자 유형)를 발생시킵니다.



Java
public class Test {  public static void main(String[] args)  {  Integer i = new Integer(5);  // Below line causes compile time error:-  // Incompatible conditional operand types  // Integer and String  System.out.println(i instanceof String);  } } 

출력 :  

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

꼭 읽어야 할 내용:

  • Java의 new 연산자와 newInstance() 메소드  
  • Java의 반사