搜索 K
Appearance
博客正在加载中...
Appearance
在继续讲注解之前,我们想看看注解的本质
@Override 例如查看 @Override 的注解源码:可以在 IDE 里按住 Ctrl 键后 点击 @Override
package java.lang;
import java.lang.annotation.*;
/**
* Indicates that a method declaration is intended to override a
* method declaration in a supertype. If a method is annotated with
* this annotation type compilers are required to generate an error
* message unless at least one of the following conditions hold:
*
* <ul><li>
* The method does override or implement a method declared in a
* supertype.
* </li><li>
* The method has a signature that is override-equivalent to that of
* any public method declared in {@linkplain Object}.
* </li></ul>
*
* @author Peter von der Ahé
* @author Joshua Bloch
* @jls 9.6.1.4 @Override
* @since 1.5
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}可以看到一个注解可以分为两部分:
//元注解
public @interface 注解名称{
属性列表;
}那个一个注解,本质上到底是什么呢?我们可以看注解被编译后,其内容是什么。
首先仿照 @Override 的格式,我们也自定义一个注解:
public @interface MyAnno {
}这就是最简单的一个注解了,可以用 @MyAnno 来使用(目前啥功能都没,我们后续再加)
在命令行里编译下
javac MyAnno.java然后用 javap 反编译:
javap MyAnno
Compiled from "MyAnno.java"
public interface MyAnno extends java.lang.annotation.Annotation {}可以看到,注解本质上就是一个接口,该接口默认继承 Annotation 接口,理论上接口能定义什么,注解就能定义什么。