Annotations und Vererbung

Thomas Darimont

Erfahrenes Mitglied
Hallo!

Hat jemand mal ein passendes Zitat zur Hand wo geschrieben steht, dass Annotations mit @Inherited Annotation nicht fuer ueberschriebene Methoden gelten?

Folgender Code:
Code:
/**
 * 
 */
package de.tutorials;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Thomas
 * 
 */
public class AnnotationInheritanceExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		System.out.println(Foo.class.isAnnotationPresent(SomeAnnotation.class));
		System.out.println(Foo.class.getMethod("foo").isAnnotationPresent(
				FancyOperation.class));

		System.out.println(Bar.class.isAnnotationPresent(SomeAnnotation.class));
		System.out.println(Bar.class.getMethod("foo").isAnnotationPresent(
				FancyOperation.class));

	}

	@SomeAnnotation
	static class Foo {
		@FancyOperation
		public void foo() {
		}
	}

	static class Bar extends Foo {
		//public void foo() { }
	}

	@Inherited
	@Retention(RetentionPolicy.RUNTIME)
	@Target(ElementType.METHOD)
	static @interface FancyOperation {
	}

	@Inherited
	@Retention(RetentionPolicy.RUNTIME)
	@Target(ElementType.TYPE)
	static @interface SomeAnnotation {
	}
}
Ergibt folgende Ausgabe:
true
true
true
true

Sobald ich den Kommentar der Zeile: //public void foo() { } entferne
ist die Ausgabe:
true
true
true
false

//Edit zu schnell:
http://www.eclipse.org/aspectj/doc/next/adk15notebook/annotations.html#annotation-inheritance
@Inherited annotations are not inherited when used to annotate anything other than a type. A type that implements one or more interfaces never inherits any annotations from the interfaces it implements.

Gruss Tom
 
Zurück