一、注解(Annotation)概述
1.注解的作用
不是程序本身,可以对程序做出解释—> 相当于注释。可以被其他程序(比如“编译器”等)读取。
2.注解的格式
注解格式为“@注释名”,还可以添加一些参数值,;例如: @SuppressWarnings(value = “unchecked”).
3.使用方式
可以附加在包(package)、类(class)、方法(method)、属性(field)中。相当于给他们添加了额外的辅助信息,我们可以通过反射机制实现对这些元数据的访问。
二、Java的内置注解
@Override:定义在java.lang.Override下,这个注解只适用于修饰方法,表示一个方法声明要重写超类中的另一个方法声明。@Deprecated : 定义在java.lang.Deprecated中,这个注解可以修饰方法、属性、类,表示不鼓励程序员使用它,通常应为它的内容很危险或者存在更好的选择。@SuppressWarning:定义在java.lang.SuppressWarning中,用来抑制编译时的警告信息,与其他两个注解有所不同,这个注解需要添加一个参数才能使用,这些参数是确定的:
@SuppressWarning(“all”)@SuppressWarning(“unchecked”)@SuppressWarning(value = {“unchecked”,“deprecation”})等等……
三. 元注解
1. 作用
负责注解其他注解,Java定义了四个标准的meta-annotation类型,他们被用来提供对其他annotation类型的说明。这些类型和他们所支持的类可以在java.lang.annotation包中找到(@Target,@Retention,@Documented,@Inherited)
2. 具体的作用
@Target: 用于描述注解的使用范围(即:被描述的注解可以用在什么地方)@Retention:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(SOURCE(源码) < CLASS(.class文件) < RUNTIME(运行时))@Documented:说明该注解将被包含在javadoc中@Inherited:说明子类可以继承父类中的该注解。
1. @Target的使用
@Target(value
= ElementType
.METHOD
)
@
interface MyAnnotation{
}
@Target(value
= {ElementType
.METHOD
,ElementType
.TYPE
})
@
interface MyAnnotation2{
}
2. @Retention的使用
@Retention(value
= RetentionPolicy
.RUNTIME
)
@
interface MyAnnotation{
}
@Retention(value
= RetentionPolicy
.SOURCE
)
@
interface MyAnnotation2{
}
3. @Documented的使用
@Documented
@
interface MyAnnotion{
}
4. @Inherited的使用
@Inherited
@
interface MyAnnotion{
}
四、自定义注解
1. 自定义注解的方法
使用@interface自定义注解,自动继承java.lang.Annotation接口
2. 注意
@interface用来声明一个注解,格式:public @interface 注解名{内容}其中的每一个方法实际上是声明了一个配置参数方法的名称就是参数的名称返回值类型就是参数的类型(返回值只能是基本类型,Class、String、enum)可以通过default来声明参数的默认值如果只有一个参数成员,一般参数名为value注解元素必须要有值,定义注解元素时,常使用空字符串,0做默认值
@Target({ElementType
.TYPE
,ElementType
.METHOD
})
@Retention(RetentionPolicy
.RUNTIME
)
@
interface MyAnnotion{
String
name() default "";
int age() default 0;
int id() default -1
String
[] schools() default{""};
public class Test{
@MyAnnotion(age
= 20,name
= "Daisy")
public void test(){}
}
@Author
S
u
g
a
r
Sugar
Sugar @Date
01
/
07
/
2020
01/07/2020
01/07/2020