笔记来源: IMOOC Java注解
按照运行机制分java
.class
文件就不存在了.class
文件中都存在按照来源分函数
@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface Description { // 使用 @interface 关键字定义注解 String desc(); // 成员以无参无异常方式声明 String author(); int age() default 18; // 能够用 default 为成员指定一个默认值 }
@interface
关键字定义注解default
为成员指定一个默认值String
、Class
、Annotation
、Enumeration
value()
,在使用时能够忽略成员名和赋值号 =
@Target
:注解的做用域code
@Retention
:注解的生命周期继承
SOURCE
:只在源码显示,编译时会丢弃CLASS
:编译时会记录到 class 中,运行时忽略RUNTIME
:运行时存在,能够经过反射读取@Inherited
:标识性注解,容许子类继承(接口实现是没有任何做用的,只会继承类注解,不会继承其余如方法的注解)@Document
:生成 javadoc 时会包含注解@Description(desc = "I am eyeColor", author = "Mooc boy", age = 18) public String eyeColor() { return "red"; }
@<注解名>(<成员名1> = <成员值1>, <成员名2> = <成员值2>, ...)
接口
概念:经过反射获取类、函数或成员上的运行时注解信息,从而实现动态控制程序运行的逻辑。生命周期
@Description(desc = "I am Example", author = "Mooc boy", age = 18) public class Example { @Description(desc = "I am eyeColor", author = "Mooc boy", age = 18) public String eyeColor() { return "red"; } }
try { // 1. 使用类加载器加载类 Class c - Class.forName("Example"); // 2. 找到类上面的注解 boolean isExist = c.isAnnotationPresent(Description.class); if (isExist) { // 3. 拿到注解实例 Description d = (Description) c.getAnnotation(Description.class); System.out.println(d.desc()); } Method[] ms = c.getMethods(); // 4-1. 找到方法上的注解 for (Method m: ms) { boolean isMExist = m.isAnnotationPresent(Description.class); if (isMExist) { Description d = (Description) c.getAnnotation(Description.class); System.out.println(d.desc()); } } // 4-2. 找到方法上的注解 for (Method m: ms) { Annotation[] as = m.getAnnotations(); for (Annotation a: as) { Description d = (Description) a; System.out.println(d.desc()); } } } catch (Exception e) { e.printStackTrace(); }
注解的做用范围 @Target
和生命周期 @Retention
ip