注解是以前忽略的一个东西,然而今后参与到正规团队开发中应该会比较重要,所以先学一学
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Outer {
String value() default "report";
int time() default 0;
}
@Outer
public class Ans {
public static void main(String[] args) {
test1();
test2();
}
static void test0() {
//注解添加于java SE5
//注解是一种特殊注释,注释会被编译器忽略,注解会被打包入class文件,因此注解是一种用作标注的元数据。
//注意!JVM不会处理注解,也不识别注解
//注解分为三类,1.由编译器使用的注解,@Override,@SuppressWarnings等,他们不进入class文件,编译后被丢弃
//2.处理class文件使用的注解,有些会进入class文件,一般都用于底层代码
//3.程序运行时读取的注解,加载后存在于JVM,是最常用的注解(java代码读取注解实现的功能,JVM不会识别注解)
//定义注解可以定义其参数,包括基本类型,String,枚举类型,以及以上三种类型的数,参数都是常数
//没有定义的参数会使用默认值
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Report {
String value() default "report";
int time() default 0;
}
@interface TT {} //博客中说所有注解都要定义Target和Retention,但是这个没有定义也可以使用,不过不知道这样的注解有没有实际意义
static void test1() {
//我们用@interface定义注解,同时使用@Target等元注解修饰定义的注解
//注解中最常用的值最好定义为value,所有值最好有default定义的默认值
//查看文件会发现存在名为Report.class与TT.class的文件,说明注解也是一个类
class A {
//! @interface Report {}
}
//! @interface Report {}
//事实证明注解的定义不能存在于方法中(不管是方法中,还是方法的内部类中都不行)
}
@TT
@Report
int i;
static void test2() {
//获取注解也是使用反射来获取
System.out.println(Ans.class.isAnnotationPresent(Report.class)); //查看一个注解是否注解了某个类,对于方法和域也相似
System.out.println(Ans.class.isAnnotationPresent(Outer.class));
Outer outer = Ans.class.getAnnotation(Outer.class); //获得一个类的注解,如果注解不存在就返回null
System.out.println(outer.value()); //注解不能直接作用于代码,需要变相相关代码才能使注解生效
}
}