• “비검사 (unchecked) 경고”란?
• 컴파일러가 타입 안정성을 확인하는데 필요한 정보가 충분치 않을 때 발생시키는 경고.
• 할 수 있는 한 모든 비검사 경고를 제거하라.
• 경고를 제거할 수 없지만 안전하다고 확신한다면 @SuppressWarnings(“unchecked”) 애노테이션을 달아 경고를 숨기자.
public class ListExample {
private int size;
Object[] elements;
public <T> T[] toArray(T[] a) {
if (a.length < size) {
/**
* 이 애노테이션을 왜 여기서 선언했는지..
*/
@SuppressWarnings("unchecked")
T[] result = (T[]) Arrays.copyOf(elements, size, a.getClass());
return result;
}
System.arraycopy(elements, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
}
• @SuppressWarnings 애너테이션은 항상 가능한 한 좁은 범위에 적용하자.
• @SuppressWarnings(“unchecked”) 애너테이션을 사용할 때면 그 경고를 무시해도 안전한 이유를 항상 주석으로 남겨야 한다.
자바 애너테이션을 정의하는 방법
@Retention: 애노테이션의 정보를 얼마나 오래 유지할 것인가.
@Target: 애노테이션을 사용할 수 있는 위치.
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface MyAnnotation {
}
---
@MyAnnotation
public class MyClass {
@MyAnnotation
public static void main(String[] args) {
// reflection
Arrays.stream(MyClass.class.getAnnotations()).forEach(System.out::println);
}
}