Java에 Annotation Inheritance와 같은 것이 있습니까?
주석을 탐색 중이며 일부 주석이 계층 구조를 갖는 것처럼 보이는 지점에 도달했습니다.
저는 주석을 사용하여 카드의 백그라운드에서 코드를 생성하고 있습니다. 카드 유형 (코드와 주석이 다름)이 다르지만 이름처럼 공통되는 특정 요소가 있습니다.
@Target(value = {ElementType.TYPE})
public @interface Move extends Page{
String method1();
String method2();
}
그리고 이것은 일반적인 주석이 될 것입니다.
@Target(value = {ElementType.TYPE})
public @interface Page{
String method3();
}
위의 예에서 Move가 method3을 상속 할 것으로 예상하지만 extends가 주석에 유효하지 않다는 경고가 표시됩니다. Annotation이 공통 기반을 확장하도록 시도했지만 작동하지 않습니다. 그게 가능할까요 아니면 디자인 문제일까요?
불행하게도. 분명히 그것은 완전히로드하지 않고 클래스의 주석을 읽는 프로그램과 관련이 있습니다. Java에서 주석을 확장 할 수없는 이유는 무엇입니까?를 참조하십시오 .
그러나 유형은 해당 주석이 인 경우 수퍼 클래스의 주석을 상속합니다 @Inherited
.
또한 상호 작용하는 데 이러한 메서드가 필요하지 않으면 클래스에 주석을 쌓을 수 있습니다.
@Move
@Page
public class myAwesomeClass {}
당신에게 효과가없는 이유가 있습니까?
상속 대신 기본 주석으로 주석을 달 수 있습니다. 이것은 Spring 프레임 워크에서 사용됩니다 .
예를 들어
@Target(value = {ElementType.ANNOTATION_TYPE})
public @interface Vehicle {
}
@Target(value = {ElementType.TYPE})
@Vehicle
public @interface Car {
}
@Car
class Foo {
}
그런 다음 Spring의 AnnotationUtils 를 Vehicle
사용하여 클래스에 주석이 추가되었는지 확인할 수 있습니다 .
Vehicle vehicleAnnotation = AnnotationUtils.findAnnotation (Foo.class, Vehicle.class);
boolean isAnnotated = vehicleAnnotation != null;
이 방법은 다음과 같이 구현됩니다.
public static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType) {
return findAnnotation(clazz, annotationType, new HashSet<Annotation>());
}
@SuppressWarnings("unchecked")
private static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType, Set<Annotation> visited) {
try {
Annotation[] anns = clazz.getDeclaredAnnotations();
for (Annotation ann : anns) {
if (ann.annotationType() == annotationType) {
return (A) ann;
}
}
for (Annotation ann : anns) {
if (!isInJavaLangAnnotationPackage(ann) && visited.add(ann)) {
A annotation = findAnnotation(ann.annotationType(), annotationType, visited);
if (annotation != null) {
return annotation;
}
}
}
}
catch (Exception ex) {
handleIntrospectionFailure(clazz, ex);
return null;
}
for (Class<?> ifc : clazz.getInterfaces()) {
A annotation = findAnnotation(ifc, annotationType, visited);
if (annotation != null) {
return annotation;
}
}
Class<?> superclass = clazz.getSuperclass();
if (superclass == null || Object.class == superclass) {
return null;
}
return findAnnotation(superclass, annotationType, visited);
}
AnnotationUtils
also contains additional methods for searching for annotations on methods and other annotated elements. The Spring class is also powerful enough to search through bridged methods, proxies, and other corner-cases, particularly those encountered in Spring.
In addition to Grygoriys answer of annotating annotations.
You can check e.g. methods for containing a @Qualifier annotation (or an annotation annotated with @Qualifier) by this loop:
for (Annotation a : method.getAnnotations()) {
if (a.annotationType().isAnnotationPresent(Qualifier.class)) {
System.out.println("found @Qualifier annotation");//found annotation having Qualifier annotation itself
}
}
What you're basically doing, is to get all annotations present on the method and of those annotations you get their types and check those types if they're annotated with @Qualifier. Your annotation needs to be Target.Annotation_type enabled as well to get this working.
참고URL : https://stackoverflow.com/questions/7761513/is-there-something-like-annotation-inheritance-in-java
'IT story' 카테고리의 다른 글
Objective-C에서`oneway void`의 사용 사례? (0) | 2020.08.12 |
---|---|
다른 스크립트에 (소스) R 스크립트를 포함하는 방법 (0) | 2020.08.12 |
C # 클래스 명명 규칙 : BaseClass 또는 ClassBase 또는 AbstractClass (0) | 2020.08.12 |
표준 C ++ 라이브러리에서`int pow (int base, int exponent)`가 아닌 이유는 무엇입니까? (0) | 2020.08.12 |
Elixir / erlang은 마이크로 서비스 접근 방식에 적합합니까? (0) | 2020.08.12 |