注解

注解

Java 语言中的类、方法、变量、参数和包等都可以被标注。和 Javadoc 不同,Java 标注可以通过反射获取标注内容。在编译器生成类文件时,标注可以被嵌入到字节码中。Java 虚拟机可以保留标注内容,在运行时可以获取到标注内容 。 当然它也支持自定义 Java 标注

package com.annotation;

import java.lang.annotation.*;
import java.util.concurrent.PriorityBlockingQueue;

//测试元注解
public class Test01 {

    @MyAnnotation
    public void test() {

    }
}


//定义一个注解
//target表示注解可以用在哪些地方
@Target(value = {ElementType.METHOD, ElementType.TYPE})

//retention表示我们的注解在什么时候有效
//runtime>class>source
@Retention(value = RetentionPolicy.RUNTIME)

//documented表示是否将注解生成在JavaDoc中
@Documented

//inherited表示子类可以继承父类的注解
@Inherited

@interface MyAnnotation {

}
package com.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//自定义注解
public class Test02 {

    @MyAnnotation2(name = "参数名测试")//参数输入没有顺序要求
    @MyAnnotation3("花生")
    public void test() {
    }


}


@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2 {
    //注解的参数: 参数类型 + 参数名()
    String name() default "";//注解可以设置默认值,如果没有默认值,使用时就必须给注解赋值

    int age() default 0;

    int id() default -1;//默认值为-1,代表不存在

    String[] schools() default {"清华大学", "北京大学"};
}


@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3 {
    String value();
}
posted @ 2022-08-03 19:11  每年桃花开的时候  阅读(35)  评论(0)    收藏  举报