使用@interface自定义注解,自动继承 java.lang.annotation接口。
-
@ interface用来声明一个注解,格式: public@ interface注解名{定义内容}
声明了一个配置参数。 -
返回值类型就是参数的类型(返回值只能是基本类型, Class, String,enum)
-
可以通过 default 来声明参数的默认值
-
如果只有一个参数成员,一般参数名为
-
注解元素必须要有值,我们定义注解元素时,经常使用空字符串,0作为默认值
import java.lang.annotation.*;
/**
* @author ASUS
*/
public class Main {
@MethodAnno
public static void main(String[] args) {
System.out.println("Hello World");
}
private int a = 1;
@MethodAnno
public void print() {
}
}
/**
* @author ASUS
* <pre>
* @Target 设置 ElementType.METHOD -> 只能把注解打到方法上
* @Rentation RententionPolicy.RUNTIME ,任何时候都有效 -> 设置注解的作用域
* @Documented 表示将注解生成到 doc 文档中
* @Inherited 表示子类可以继承源注解
*
* 以上称为源注解
*
* </pre>
*/
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.METHOD)
@Documented
@interface MethodAnno{
}
元注解:
元注解就是 java 提供的 用来注解其他注解的注解,java 定义了 4个 标准的 meta-annotation类型,他们被用来提供对其他 annotation
内置注解:
@Override, 用来编译确认
@Depricated, lang包下面,在此注释可以用于修饰方法,属性,类表示不鼓励程序员使用下面的类,因为它很危险,有更好的选择
@SuppressWarnings: 定义在 java.lang表下面,用来抑制编译时候的警告信息,与前面两个注释有所不同,你需要添加一个参数才可能正常使用。这些参数都是已经定义好了的。
我们选择使用即可,
@SuppressWarning(“all”)
@SuppressWarning(“unchecked”)
@SuppressWarning({“unchecked”,“deprecation”})
注意:
Annotation 是 jdk5.0 开始使用的新技术
Annotation 的作用:
- 不是程序,只是对程序做出一定的解释(和注释基本没什么区别)
- 注解可以附加在 package,class,method,field 等上面,相当于给他们添加了额外的辅助信息,我们可以通过反射机制编程实现这些元数据的访问
Target 注解的 声明源码:
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
}
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
runtime > class > source
这是 java.lang 包的目录