@SuppressWarnings 和其他自定义注释在内部如何工作?

How does @SuppressWarnings and other custom annotation work internally?

我很困惑@SuppressWarnings 是如何在内部工作的。如果我们看到它的源代码,它是这样的:

@Retention(SOURCE)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
public @interface SuppressWarnings
{
  String[] value();
}

现在,如果我们看到它在代码中得到实现,就像,

@SuppressWarnings({"unused"})
public static void main(String args[]){
int i;
}

所以问题是:-

1) 一旦我们将 "unused" 作为参数传递,eclipse 就会停止抛出警告。同样,我们可以使用 "unchecked"、"deprecation" 等。那么它是如何工作的呢?我的意思是我们在@interface 中只有一个名为 value() 的方法,它的 return 类型是 String[]。所以它做了一切,怎么做?为什么方法的名字是value()?此方法是否具有某些特殊意义,可以在内部执行某些操作以捕获 "unused"?

等参数

2) 有时我们可以看到在某些@interface 中有如下指定的默认值。那么什么是默认值?从 java8 我们有了默认方法的新概念。但此默认值也用于 java 的低版本。这是如何工作的,它是什么?这是低于 java8 版本的关键字吗?

public @interface MyIntf{

    /**
     * The error message.
     */
    String message() default "My Default Message";

    /**
     * The group.
     */
    Class<?>[] groups() default {};

    /**
     * the payload.
     */
    Class<? extends Payload>[] payload() default {};
}

注释没有做任何事情。它就在那里,在源代码中。

Eclipse 编译器,当它在方法(或 class,或构造函数等)上看到一个时,只是不会发出一些通常会发出的警告,具体取决于在注释的 value 属性。

why the name of method is value()

因为这是注释的设计者选择的属性名称。它可以被命名为任何东西。使用 "value" 作为它的名字的好处是它允许写

@SuppressWarnings("unused")

而不必写

@SuppressWarnings(value = "unused")

关于默认关键字:

String message() default "My Default Message";

这只是简单的说,如果你不显式地为注解的message属性指定一个值,它的值为"My Default Message"

您在问 2 个不同的问题。我会分开回答。

As soon as we pass "unused" as a parameter, the eclipse stops throwing warning. Similarly, we can use "unchecked", "deprecation" , etc. So how does it work?

@SuppressWarning 是一个特殊的注释,因为 java 编译器知道它。当编译器编译 类 并发现警告时,它会查看该代码上是否有任何 @SuppressWarning 注释,如果有,它应该抑制哪些警告。有一个字符串名称到编译器警告的映射,所以它知道哪些警告不要打印出来。这是我在另一个 SO 问题中找到的列表:

What is the list of valid @SuppressWarnings warning names in Java?

Eclipse 不断地动态编译您的代码,因此它会看到您的@SuppressWarning 并在触发重新编译时(通常在保存时)开始忽略警告

Sometime we can see that there is default as specificed below in some @interface. So what is default?

默认是用户未指定值时使用的默认值。因此,在您的示例中,您可以指定这样的消息:

@MyInf(message="my custom message")

如果您没有指定 @MyInf 之类的消息,则消息设置为 "My Default Message"