programing

Java에서 "instance of" 사용

prostudy 2022. 7. 21. 23:58
반응형

Java에서 "instance of" 사용

'instance of' 연산자는 어디에 사용됩니까?

자바가 그 기능을 가지고 있다는 걸 알았어요.instanceof교환입니다.어디에 쓰이고 어떤 장점이 있는지 자세히 설명해 주시겠습니까?

기본적으로 개체가 특정 클래스의 인스턴스인지 확인합니다.일반적으로 슈퍼 클래스 또는 인터페이스 유형의 객체에 대한 참조 또는 매개변수가 있고 실제 객체에 다른 유형(보통 더 구체적)이 있는지 확인해야 할 때 사용합니다.

예:

public void doSomething(Number param) {
  if( param instanceof Double) {
    System.out.println("param is a Double");
  }
  else if( param instanceof Integer) {
    System.out.println("param is an Integer");
  }

  if( param instanceof Comparable) {
    //subclasses of Number like Double etc. implement Comparable
    //other subclasses might not -> you could pass Number instances that don't implement that interface
    System.out.println("param is comparable"); 
  }
}

이 연산자를 자주 사용해야 하는 경우 일반적으로 설계에 몇 가지 결함이 있음을 암시합니다.따라서 잘 설계된 응용 프로그램에서는 해당 연산자를 가능한 한 적게 사용해야 합니다(물론 해당 일반 규칙에는 예외가 있습니다).

instanceof는 객체가 클래스의 인스턴스인지, 서브클래스의 인스턴스인지, 특정 인터페이스를 구현하는 클래스의 인스턴스인지를 확인하기 위해 사용합니다.

Oracle 언어 정의의 자세한 내용은 여기를 참조하십시오.

instanceof를 사용하여 객체의 실제 유형을 확인할 수 있습니다.

class A { }  
class C extends A { } 
class D extends A { } 

public static void testInstance(){
    A c = new C();
    A d = new D();
    Assert.assertTrue(c instanceof A && d instanceof A);
    Assert.assertTrue(c instanceof C && d instanceof D);
    Assert.assertFalse(c instanceof D);
    Assert.assertFalse(d instanceof C);
}

instanceof는 객체가 지정된 유형인지 테스트하기 위해 사용할 수 있는 키워드입니다.

예:

public class MainClass {
    public static void main(String[] a) {

    String s = "Hello";
    int i = 0;
    String g;
    if (s instanceof java.lang.String) {
       // This is going to be printed
       System.out.println("s is a String");
    }
    if (i instanceof Integer) {
       // This is going to be printed as autoboxing will happen (int -> Integer)
       System.out.println("i is an Integer");
    }
    if (g instanceof java.lang.String) {
       // This case is not going to happen because g is not initialized and
       // therefore is null and instanceof returns false for null. 
       System.out.println("g is a String");
    } 
} 

여기 제 정보원이 있습니다.

언급URL : https://stackoverflow.com/questions/7526817/use-of-instanceof-in-java

반응형