1、定义:
Java提供了一种源程序中的元素关联任何信息和任何元数据的途径和方法;
2、注解的分类
2.1 按照运行机制分
|- 源码注解 注解只在源码中存在,编译成*.class文件就不存在了;
|- 编译时注解 注解在源码和*.class文件中都存在;像@Override、@Deprecated、@Suppvisewarnings;
|- 运行时注解 在运行阶段还起作用,甚至会影响运行逻辑的注解;像@Autowired;
2.2 按照来源分
|- 来自JDK
|- 来自第三方
|- 自定义注解
2.3 元注解 - 注解的注解
3、自定义注解:
示例:
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description {
String desc();
String author();
int age() default 18;
}
3.1 自定义注解的语法要求:
使用@interface关键字定义注解;
成员以无参数无异常的方式声明;
可以用default为成员指定默认值;
成员类型是受限的,合法的类型包括基本数据类型及String、Class、Annotation、Enumeration;
如果注解只有一个成员,则成员名必须取名为value(),在使用时可以忽略成员名和赋值等号;
注解可以没有成员,没有成员的注解成为标识注解;
元注解:
Target - 注解的作用域
CONSTRUCTOR 构造方法声明
FIELD 字段声明
LOCAL_VARIABLE 局部变量声明
METHOD 方法声明
PACKAGE 包声明
PARAMETER 参数声明
TYPE 类,接口
@Retention - 生命周期
SOURCE 只在源码显示,编译时丢弃
CLASS 编译时会记录到class中,运行时忽略
RUNTIME 运行时存在,可以通过反射读取
@Inherited - 标识注解,允许子注解继承
@Documented - 生成javadoc时会包含注解
3.2 使用自定义注解
示例:
@Description(desc = "I am eyeColor", author = "hellboy", age = 18)
public String eyeColor() {
return "red";
}
语法:
@<注解名>(<成员名1>=<成员值1>, <成员名2>=<成员值2>, ...)
4、解析注解
通过反射获取类、函数或成员上的运行时注解信息,从而实现动态控制程序运行的逻辑;
两种解析方式:
public static void main(String[] args) {
try {
Class c = Class.forName("com.yiniu.study.controller.TestDemo");
boolean isExist = c.isAnnotationPresent(Description.class);
if (isExist) {
Description d = (Description) c.getAnnotation(Description.class);
System.out.println(d.value());
}
Method[] methods = c.getMethods();
for (Method method : methods) {
boolean isMethodExist = method.isAnnotationPresent(Description.class);
if (isMethodExist) {
Description de = method.getAnnotation(Description.class);
System.out.println(de.value());
}
}
Annotation[] classAnnotations = c.getAnnotations();
for (Annotation annotation : classAnnotations) {
if (annotation instanceof Description) {
Description d = (Description) annotation;
System.out.println(d.value());
}
}
for (Method method : methods) {
Annotation[] annotations = method.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof Description) {
Description d = (Description) annotation;
System.out.println(d.value());
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
2053

被折叠的 条评论
为什么被折叠?



