2023-java-study / book-study

북 스터디 기록 레포지토리
0 stars 0 forks source link

[item 33] Class<? extends Annotation> 형변환 #108

Open NuhGnod opened 1 year ago

NuhGnod commented 1 year ago

p.204 객체를 Class<? extends Annotation>으로 형변환할 수도 있지만, 이 형변환은 비검사이므로 컴파일하면 경고가 뜰 것이다. 위 문장에서 말하고 있는 형변환의 예시가 있었으면 좋겠습니다!

gmelon commented 1 year ago
String annotationName = "org.springframework.web.bind.annotation.GetMapping"; // 런타임에 동적으로 입력된다고 가정

// 비검사 형변환 (경고 발생)
Class<? extends Annotation> classAnnotation1 = (Class<? extends Annotation>) Class.forName(annotationName);

// Class 의 asSubClass() 를 사용한 형변환
Class<?> classAnnotation2 = Class.forName(annotationName);
classAnnotation2.asSubclass(Annotation.class);

System.out.println("classAnnotation1 = " + classAnnotation1);
System.out.println("classAnnotation2 = " + classAnnotation2);

// classAnnotation1 = interface org.springframework.web.bind.annotation.GetMapping
// classAnnotation2 = interface org.springframework.web.bind.annotation.GetMapping

이런 상황을 생각해볼 수 있을 것 같습니다.

Class 클래스에게 형변환을 위임해서 경고 발생 없이 런타임에 형변환을 수행할 수 있게 됩니다.

물론 Class 클래스 입장에서는 또 다시 비검사 형변환이므로 아래와 같이 unchecked 를 supressed 하고 있습니다.

image