gpt4 book ai didi

java - 是否可以在返回类型上添加注释

转载 作者:搜寻专家 更新时间:2023-10-31 08:14:43 25 4
gpt4 key购买 nike

我遇到了这段代码

@Override
public @NotNull Class<?> getProviderClass() {
return this.getClass();
}

我想知道它是否与下面的代码相同:

@Override
@NotNull
public Class<?> getProviderClass() {
return this.getClass();
}

注意:@NotNull注解相对于accessModifier处于不同的位置

注解在这种情况下是在返回类型上还是在方法上?

最佳答案

Java 8 允许类型注释,也就是像 @Foo int foo = (@Foo int) var; 这样的东西。

规范的总结是,它取决于如何声明@NonNull注解,特别是如何指定它的@Target

  • 如果它使用 ElementType.TYPE_USE,则注释适用于返回类型。
  • 如果它使用ElementType.METHOD,它适用于方法声明。
  • 如果同时使用(或不使用),则它适用于返回类型和方法声明。

无论哪种方式,注释语法上都是方法的修饰符,因此它的位置无关紧要。

因此,例如,如果 @NonNull 被声明为类型注释,那么是的,您断言该方法的返回值不应为 null。

9.7.4 :

It is possible for an annotation to appear at a syntactic location in a program where it could plausibly apply to a declaration, or a type, or both. This can happen in any of the five declaration contexts where modifiers immediately precede the type of the declared entity:

  • Method declarations (including elements of annotation types)

  • Constructor declarations

  • Field declarations (including enum constants)

  • Formal and exception parameter declarations

  • Local variable declarations (including loop variables of for statements and resource variables of try-with-resources statements)

The grammar of the Java programming language unambiguously treats annotations at these locations as modifiers for a declaration, but that is purely a syntactic matter. Whether an annotation applies to a declaration or to the type of the declared entity - and thus, whether the annotation is a declaration annotation or a type annotation - depends on the applicability of the annotation's type:

  • If the annotation's type is applicable in the declaration context corresponding to the declaration, and not in type contexts, then the annotation is deemed to apply only to the declaration.

  • If the annotation's type is applicable in type contexts, and not in the declaration context corresponding to the declaration, then the annotation is deemed to apply only to the type which is closest to the annotation.

  • If the annotation's type is applicable in the declaration context corresponding to the declaration and in type contexts, then the annotation is deemed to apply to both the declaration and the type which is closest to the annotation.

In the second and third cases above, the type which is closest to the annotation is the type written in source code for the declared entity; if that type is an array type, then the element type is deemed to be closest to the annotation.

关于java - 是否可以在返回类型上添加注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35875389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com