JavaJava 杂谈Java Web知识

注解

2018-05-13  本文已影响2人  Java酸不酸

jdk中三种常见的注解:(注解与类、接口平级存在)

  1. Override:用于描述方法重写,描述该方法是从父类继承的
  2. SuppressWarnings:压制警告的意思
  3. Deprecated:用于描述方法过期了

注解属性的类型可以是哪些?

  1. 基本数据类型都可以:byte、short、int、long、float、double、char、boolean
  2. String
  3. 注解类型
  4. Class类型
  5. 枚举类型
  6. 以上类型的一维数组
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation02 {
    String str();
    int num() default 10;
    MyAnnotation01 anno();
    Class clazz();
    Color color();
    String[] value();
}

使用注解

如果使用的那个注解有注解属性,那么使用的时候就要为这些注解属性赋值。

@MyAnnotation02(anno = @MyAnnotation01, clazz = TestAnno03.class, color = Color.GREEN, str = "qwe", value = { "asd" })
public class TestAnno03 {
    @MyAnnotation03(value = "qwe")
    public String name = "张三";
    
    @MyAnnotation03(value = "qwe")
    public TestAnno03() {
    }
    
    @MyAnnotation03(value = "qwe")
    @MyAnnotation01
    public void fn1(){
        @MyAnnotation03(value = "qwe")
        int num = 20;
    }
}

元注解就是定义在注解上的注解

@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD,ElementType.TYPE,ElementType.LOCAL_VARIABLE,ElementType.FIELD,ElementType.CONSTRUCTOR })
public @interface MyAnnotation03 {
    String value();
}

解析注解

// 获取该类字节码文件对象,Class类实现了AnnotatedElement接口,所以就有该接口的的那四个方法
Class<?> clazz = Class.forName("com.itheima.annotation.meta.TestAnno03");
Annotation[] annotations = clazz.getAnnotations();
// 获取字节码文件对象
Class<?> clazz = Class.forName("com.itheima.annotation.meta.TestAnno03");
// 获取所有的字段
Field field = clazz.getField("name");
boolean flag = field.isAnnotationPresent(MyAnnotation03.class);
System.out.println(flag);
Class<?> clazz = Class.forName("com.itheima.annotation.meta.TestAnno03");
//获取fn1方法
Method method = clazz.getMethod("fn1");
        
MyAnnotation01 annotation = method.getAnnotation(MyAnnotation01.class);
System.out.println(annotation);

上一篇 下一篇

猜你喜欢

热点阅读