4

Добрый день.

Если используем аннотации, к примеру, для класса. У нас есть некий абстрактный класс А. У него есть предок, класс B. И там и там есть аннотация @MyAnnotation. В аннотации есть поле

String[] value() default {};

В итоге получили примерно такое:

@MyAnnotation({"str1","str2"})
abstract class A {}

@MyAnnotation({"str3","str4"})
class B extends A {}

Вопрос: Будут ли суммироваться все значения из класса и суперкласса, или просто возьмется значение из текущего объекта B. Либо, может, еще какие хитрости есть в аннотациях?

1 ответ 1

5

Наследование аннотаций возможно при использовании аннотации @Inherited. В вашем случае произойдет просто перекрытие.

Аннотации

@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface InheritedAnnotation {
    String name();
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface UninheritedAnnotation {
    String name();
}

Тестовые классы

@InheritedAnnotation(name = "A1")
public class A1 {}

@InheritedAnnotation(name = "B1")
public class B1 extends A1 {}

public class C1 extends A1 {}

@UninheritedAnnotation(name = "A2")
public class A2 {}

@UninheritedAnnotation(name = "B2")
public class B2 extends A2 {}

public class C2 extends A2 {}

Тест

@Test
public void test() throws Exception {
    System.out.println(new A1().getClass().getAnnotation(InheritedAnnotation.class));
    System.out.println(new B1().getClass().getAnnotation(InheritedAnnotation.class));
    System.out.println(new C1().getClass().getAnnotation(InheritedAnnotation.class));
    System.out.println(new A2().getClass().getAnnotation(UninheritedAnnotation.class));
    System.out.println(new B2().getClass().getAnnotation(UninheritedAnnotation.class));
    System.out.println(new C2().getClass().getAnnotation(UninheritedAnnotation.class));
}

Вывод

//@org.example.InheritedAnnotation(name=A1)
//@org.example.InheritedAnnotation(name=B1)
//@org.example.InheritedAnnotation(name=A1)
//@org.example.UninheritedAnnotation(name=A2)
//@org.example.UninheritedAnnotation(name=B2)
//null
1
  • Стоит отметить, что даже @Inherited не позволяет наследовать аннотации от интерфейсов. 31 мар 2016 в 10:13

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.