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() 方法。

SDLCのライフサイクル
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

注記: インスタンス化していない他のクラスとオブジェクトをチェックすると、instanceof 演算子はコンパイル時エラー (互換性のない条件オペランド タイプ) をスローします。



xd xd 意味
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 でのリフレクション