类型级别的注释是否总是会被该类型的公共方法继承?

huangapple go评论71阅读模式
英文:

Is a type-level annotation always inherited by public methods of that type?

问题

以下是翻译好的部分:

这是否始终成立:

public interface Foo {
  
  @MyCustomAnnotation
  void bar();

  @MyCustomAnnotation
  void bar2();
}

等价于:

@MyCustomAnnotation
public interface Foo {
  
  void bar();

  void bar2();
}

或者这取决于注解的定义方式?换句话说,类/接口级别的注解是否总是会被该类型的方法继承(只要该方法未标记有此注解)?

具体而言,如果我将上述注解定义为:

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
}

方法会从所在的类/接口继承这个注解吗?

英文:

Is it always the case that the following

public interface Foo {

  @MyCustomAnnotation
  void bar();

  @MyCustomAnnotation
  void bar2();
}

Is equivalent to

@MyCustomAnnotation
public interface Foo {
    
  void bar();

  void bar2();
}

Or does it depend on how the annotation is defined? In other words, are class/interface-level annotations always inherited by methods of that type (as long as the method isn't also marked with this annotation)?

Specifically, if I define the annotation above as

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
}

Will methods inherit this annotation from the surrounding class/interface?

答案1

得分: 4

从来都不是这样,除非解释注释的库明确决定将类型级别的注释视为默认值(例如,Spring 的 @Transactional)。即使在这种情况下,库中编写的代码是否将类级别和方法级别的注释组合(@RequestMapping)或替换(@Transactional)定义,完全取决于库内的代码。

英文:

It is never the case that they are equivalent unless the library interpreting the annotation specifically decides to treat the type-level annotation as a default (e.g., Spring's @Transactional). Even then, it is entirely up to the code written in the library whether a combination of class-level and method-level annotations result in combination (@RequestMapping) or replacement (@Transactional) of definitions.

huangapple
  • 本文由 发表于 2020年8月26日 05:34:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63587444.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定