使用注解比接口类型有什么优势?

What is the advantage of using annotation over interface type?

在此example中,注释类型下方(@interface):

@interface ClassPreamble {
       String author();
       String date();
       int currentRevision() default 1;
       String lastModified() default "N/A";
       String lastModifiedBy() default "N/A";
       // Note use of array
       String[] reviewers();
    }

编译为 interface 类型:

interface annotationtype.ClassPreamble extends java.lang.annotation.Annotation{
    public abstract java.lang.String author();
    public abstract java.lang.String date();
    public abstract int currentRevision();
    public abstract java.lang.String lastModified();
    public abstract java.lang.String lastModifiedBy();
    public abstract java.lang.String[] reviewers();
}

因此,注释类型在运行前被编译为 interface 类型。

在java中,使用注释类型(@interface)比interface类型有什么优势?

如果您手动执行编译器自动执行的操作,则不会定义注释。根据Oracle documentation,

an interface that manually extends [java.lang.annotation.Annotation] does not define an annotation type.

因此,@interface语法需要在Java中定义注释。

接口是一种对象建模技术,它允许对象实现与多种类型关联的行为(但不是状态)。

注解是一种在代码中嵌入类型元数据的技术;此元数据旨在由工具(测试框架、代码生成器等)使用,但它们没有语言级语义。您可以将它们视为附加到某些程序元素的 structured/typed 注释,可以通过反射访问它们。

在幕后,注释作为接口实现,主要是为了方便,但这种相似性可能更令人困惑,而不是有助于理解它们的用途。