版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_1018944104/article/details/82914464
一、注解的概念和作用
- 从JDK5开始,Java增加了对元数据(MetaData)的支持,就是注解Annotation;
- 注解是指代码里的特殊标记,这些标记可以在编译、类加载、运行时被读取,并执行相应的处理。
二、基本注解
- @override 方法重写
- @Deprecated 过期
- @SupperessWarnings 压制警告。使用方式,@Supperesswarning("all")或者@Supperesswarning("rawtypes", "unuserd")
- all 压制类中所有警告
- rawtypes 压制原生警告
- unchecked 压制未检查警告
- unused 压制未使用警告
- serial 压制序列号警告
- @FunctionalInterface 函数式接口
三、Java元注解
1.@Target 修饰哪些程序元素
ElementType:
- CONSTRUCTOR 构造方法声明
- FIELD 字段声明(包含枚举常量)
- LOCAL_VARIABLE 局部变量声明
- METHOD 方法声明
- PACKAGE 包声明
- PARAMETER 参数声明
- TYPE 类、接口(包含注释类型)或枚举声明
2.@Retention 注解保留时间
RetentionPolicy 是个枚举,其值只能是如下三个:
- RetentionPolicy.SOURCE
- RetentionPolicy.CLASS(这是默认值)
- RetentionPolicy.RUNTIME
3.@Inherited 继承性说明
- 指定被修饰的Annotation将具有继承性,即如果某个类使用某个注解,则其子类将自动被某个注解修饰。
- 属性只要是Public修饰的,那么该属性的注解可以被子类继承,和类注解继承不太一样。
4.@Documented 提取生成文档
- 被修饰的注解会被提出来生成帮助文档的一部分。
四、自定义注解及使用
1.语法格式
@interface 注解名{
类型 成员名() default 默认值;
……
}
2.示例:自定义注解及其使用方式
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Arrays;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@interface FuitAnno{
public String value() default "apple";
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface ColorAnno{
public Color color() default Color.RED;
}
//若不赋值,则反射获取时使用注解默认值apple
@FuitAnno("orange")
class Fuit{
public String name;
}
enum Color{
RED,GREEN,YELLOW;
}
class Apple extends Fuit{
int szie;
//颜色
@ColorAnno(color=Color.YELLOW)
Color colorName;
}
public class TestAnno {
public static void main(String[] args) throws Exception {
//反射技术获得注解信息
//Fuit注解信息
// Class<?> c = Class.forName("day21_0930.Fuit");
// Annotation[] annos = c.getDeclaredAnnotations();
// Arrays.stream(annos).forEach(System.out::println);
//Apple注解信息
Class<?> c1 = Class.forName("day21_0930.Apple");
//获得子类继承父类的类型上的注解信息
Annotation[] annos1 = c1.getAnnotations();
Arrays.stream(annos1).forEach(System.out::println);
//获取属性上的注解信息
Annotation[] annos2 = c1.getDeclaredField("colorName").getDeclaredAnnotations();
Arrays.stream(annos2).forEach(System.out::println);
}
}