आप विरासत के बजाय आधार एनोटेशन के साथ अपनी एनोटेशन को एनोटेट कर सकते हैं। यह used in Spring framework है।
एक उदाहरण
@Target(value = {ElementType.ANNOTATION_TYPE})
public @interface Vehicle {
}
@Target(value = {ElementType.TYPE})
@Vehicle
public @interface Car {
}
@Car
class Foo {
}
तो आप देख सकते हैं एक वर्ग Vehicle
Spring's AnnotationUtils उपयोग करने के साथ टिप्पणी की जाती है देने के लिए:
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
:
Vehicle vehicleAnnotation = AnnotationUtils.findAnnotation (Foo.class, Vehicle.class);
boolean isAnnotated = vehicleAnnotation != null;
इस विधि के रूप में कार्यान्वित किया जाता है अतिरिक्त विधियां भी शामिल हैं विधियों और अन्य एनोटेटेड तत्वों पर टिप्पणियों की खोज के लिए। वसंत वर्ग भी ब्रिज किए गए तरीकों, प्रॉक्सी, और अन्य कोने-मामलों, विशेष रूप से वसंत में आने वाले लोगों के माध्यम से खोजने के लिए पर्याप्त शक्तिशाली है।
स्रोत
2013-09-03 06:47:04
एनोटेशन विरासत एनोटेशन के आधार पर डीएसएल बनाने के लिए जरूरी है। इस तरह की करुणा है कि एनोटेशन विरासत समर्थित नहीं है। – Ceki
मैं सहमत हूं, ऐसा करने के लिए एक प्राकृतिक चीज़ की तरह लगता है। विशेष रूप से जावा पर विरासत को समझने के बाद, आप उम्मीद करते हैं कि यह सब कुछ पर लागू हो। – javydreamercsw