Java注解学习

为什么要学习注解

  1. 看懂别人的代码
  2. 会用注解 编程简洁 代码清晰
  3. 让别人高看一眼(会自定义注解)

注解的概念

Java 提供了一种原程序中的元素关联任何信息和任何元数据的途径和方法。

Java中的常见注解

@Override
@De

注解的分类

  1. 源码注解:注解只在源码中存在,编译称.class 文件就不存在了。
  2. 编译时注解:注解在源码和编译文件中都存在。
  3. 运行时注解:在运行阶段仍旧起作用,甚至会影响运行逻辑的注解。
  4. 元注解:注解的注解

自定义注解的语法要求

  1. 类使用@interface 关键字定义注解
  2. 注解的成员类型是受限的,合法的类型包括原始类型及String,Class,Annotation,Enumeration
  3. 如果注解只有一个成员,则成员名必须为value() ,在使用时可以忽略成员名和赋值号(=)
  4. 注解可以没有成员,称为标示注解
public @interface Description{
    String desc(); // 成员无参 无异常抛出
    String author();
    int age() default 18;
}

元注解

@Target({ElementType.METHOD,ElementType.TYPE})// 注解的作用域
@Retention(RetentionPolicy.RUNTIME)// 生命周期 source class runtime
@Inherited //  允许子类继承
@Documented // 生成 javadoc 的时候会包含注解信息
public @interface Description {
    String desc();
    String author();
    int age() default 18;
}

使用自定义注解

    @<注解名>(<成员名1>=<成员值1>,<成员名2>=<成员名2>,...)

    @Description(desc = "I am eyeColor",author = "Somebody",age = 18)
    public String eyeColor(){
        return "red";
    }

解析注解

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

public class ParseAnn {
    public static void main(String[] args){
        // 1. 使用类加载器加载类
        try {
            Class c = Class.forName("MapDemo");
            //2 找到类上面的注解
            boolean isExist = c.isAnnotationPresent(Description.class);
            if (isExist){
                // 3. 拿到注解实例
                Description d = (Description) c.getAnnotation(Description.class);
                System.out.print(d.desc());
            }
            // 4. 找到方法上的注解
            Method[] ms = c.getMethods();
            for (Method m:ms
                 ) {
                boolean isMExist = m.isAnnotationPresent(Description.class);
                if (isMExist){
                    Description d = m.getAnnotation(Description.class);
                    System.out.print(d.desc());
                }

            }
            for (Method m:ms
                 ) {
                Annotation[] as = m.getAnnotations();
                for (Annotation a: as
                     ) {
                    if (a instanceof Description){
                        Description d = (Description) a;
                        System.out.print(d.desc());
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

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