面试官问你注解,不慌!快看这篇文章

自定义注解

在这里插入图片描述

 @interface 使用 @interface 关键字定义注解
 
 String value() default ""; 
  成员变量 只有一个必须是value   默认值:defaule ""
  成员变量类型是受限的,合法的类型包括原始类型及String,Class,annotation,Enumeration。
  可以没有成员变量 :称之为标识注解
  

@Target 作用域
@Target:指定被修饰的Annotation可以放置的位置(被修饰的目标)
@Target(ElementType.TYPE) //接口、类
@Target(ElementType.FIELD) //属性
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法参数
@Target(ElementType.CONSTRUCTOR) //构造函数
@Target(ElementType.LOCAL_VARIABLE) //局部变量
@Target(ElementType.ANNOTATION_TYPE) //注解
@Target(ElementType.PACKAGE) //包
@Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS) //默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME) //注解会在class字节码文件中存在,在运行时可以通过反射获取到

@Inherited 允许被子类继承
@Documented  表示生成javadoc时会包含注解

实践

1. 定义一个注解类

@Target({ElementType.METHOD})
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotion {
    String value();
}

2. 定义一个类 在类的一个方法中加上注解

public class Demo {

    @MyAnnotion("test")
    public void test() {
    }
}

3. 获取注解内容

public class Test {
    public static void main(String[] args) {

        //使用类加载器 加载类
        try {
            Class<?> aClass = Class.forName("com.smile.annotion.Demo");

            Method test = aClass.getMethod("test");
            //判断 这个方法有没有自定义注解
            boolean annotationPresent = test.isAnnotationPresent(MyAnnotion.class);
            if (annotationPresent){
                //含有自定义注解
                MyAnnotion annotation = test.getAnnotation(MyAnnotion.class);
                //打印注解
                System.out.println(annotation.value());
            }
        } catch (ClassNotFoundException | NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章