Java--注解

2017-01-14  本文已影响41人  年少懵懂丶流年梦
1、概念

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

2、Java中的常见注解

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

第三方注解

3、注解的分类
  1. 按照运行机制分为
  1. 按照来源分为
  1. 元注解 (注解的注解)
4、自定义注解

自定义注解的语法要求


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

注解的注解(元注解)


框中的就是元注解。

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

@Target 注解的作用域:

@Retention(RetentionPolicy.RUNTIME)

@Retention 生命周期

@Inherited 

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

@Documented 

生成javadoc的时候包含注解

使用自定义注解

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

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类型。

上一篇 下一篇

猜你喜欢

热点阅读