Java--注解

1、概念

注解:(JDK1.5)
是Java提供的一种 源程序中的元素关联任何信息和任何元数据的途径和方法。

2、Java中的常见注解

JDK自带注解
@Override 对父类方法的重写
@Deprecated 表示接口中的方法已经过时
@SuppressWarnings("deprecation") 通知java编译器忽略特定的编译警告

第三方注解

  • spring:
    @AutoWired
    @Service
    @Repository
  • Mybatis:
    @InsertProvider
    @UpdateProvider
    @Options
3、注解的分类
  1. 按照运行机制分为
  • 源码注解:注解只在源码中存在,编译成.class文件就不存在了
  • 编译时注解:注解在源码和.class文件中都存在(如:JDK内置系统注解(自带的注解))
  • 运行时注解:在运行阶段还起作用,甚至会影响运行逻辑的注解(如:Spring中@Autowried)
  1. 按照来源分为
  • JDK内置系统注解
  • 自定义注解
  • 第三方注解
  1. 元注解 (注解的注解)
4、自定义注解

自定义注解的语法要求

Java--注解_第1张图片
Java--注解_第2张图片

原始类型就是基本的数据类型。

注解的注解(元注解)

Java--注解_第3张图片

框中的就是元注解。

@Target({ElementType.CONSTRUCTOR,ElementType.FIELD,ElementType.METHOD})

@Target 注解的作用域:

  • CONSTRUCTOR 构造方法声明
  • FIELD 字段声明
  • LOCAL_VARIABLE 局部变量声明
  • METHOD 方法声明
  • PACKAGE 包声明
  • PARAMETER 参数声明
  • TYPE 类接口。
@Retention(RetentionPolicy.RUNTIME)

@Retention 生命周期

  • SOURCE 只在源码显示,编译时会丢弃
  • CLASS 编译时会记录到class中,运行时忽略
  • RUNTIME 运行时存在,可以通过反射读取。
@Inherited 

@Inherited 允许子类继承
@Inherited(子类是否可继承) 对接口interface、方法继承没有作用,对类才有效。也就是说,继承只会继承类上的注解,而不会继承方法上的注解

@Documented 

生成javadoc的时候包含注解

使用自定义注解

Java--注解_第4张图片

解析注解
概念:通过反射获取类、函数或成员上的运行时注解信息,从而实现动态控制程序运行的逻辑。

public static void main(String[] args) {
        // 1.使用类加载器加载类
        try{
            Class c= Class.forName("com.ann.test.Child");
            // 2.找到类上面的注解
            boolean isExit = c.isAnnotstionPresent(Desription.class);
            //判断类上是否有description这个注解
            if(isExit){
                //3.拿到注解实例
                Description d = (Description)c.getAnnotation(Description.class);
                System.out.println(d.value());
            }
            //4.找到方法上的注解
            Method[] ms= c.getMethods();
            for(Method m:ms){
                boolean isMexist = m.isAnnotationPresent(Description.class);
                if (isMexist) {
                    Description d = (Description)m.getAnnotation(Description.class);
                    System.out.print(d.value());
                }
            }

            //另一种解析方法
            for(Method m :ms){
                Annotation[] as = m.getAnnotations();
                for(Annotation a : as){
                    if (a instanceof Description) {
                        Description d = (Description)a;
                        System.out.println(d.value());                      
                    }
                }
            }   
        }catch(ClassNotFoundException e){
          e.printStackTrace();
        }
    }

Ps1:RetentionPolicy.RUNTIME时,才能获取到注解,SOURCE和CLASS都获取不到注解。
Ps2:@Inherited对implements不起作用,对extends起作用(只会继承类上面注解,而不会继承该类方法中的注解)。
Ps3:instanceof概念:用来判断内存中实际对象A是不是B类型。

你可能感兴趣的:(Java--注解)