注解的定义
用@interface表示。
元注解
@interface上面按需要注解上一些东西,包括@Retention、@Target、@Document、@Inherited四种。
注解的保留策略
@Retention(RetentionPolicy.SOURCE) // 注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得
@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
注解的作用目标
@Target(ElementType.TYPE) // 接口、类、枚举、注解
@Target(ElementType.FIELD) // 字段、枚举的常量
@Target(ElementType.METHOD) // 方法
@Target(ElementType.PARAMETER) // 方法参数
@Target(ElementType.CONSTRUCTOR) // 构造函数
@Target(ElementType.LOCAL_VARIABLE) // 局部变量
@Target(ElementType.ANNOTATION_TYPE) // 注解
@Target(ElementType.PACKAGE) // 包
注解包含在javadoc中
@Documented
注解可以被继承
@Inherited
示例:自定义注解
package annotation;
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;
@Documented
@Inherited
@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Init {
public String value() default "";
}
示例:获取注解的值
package factory;
import java.lang.reflect.Method;
import annotation.Init;
import model.User;
/**
* UserFactory.java
*
*/
public class UserFactory {
public static User create() {
User user = new User();
// 获取User类中所有的方法(getDeclaredMethods也行)
Method[] methods = User.class.getMethods();
try {
for (Method method : methods) {
// 如果此方法有注解,就把注解里面的数据赋值到user对象
if (method.isAnnotationPresent(Init.class)) {
Init init = method.getAnnotation(Init.class);
method.invoke(user, init.value());
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return user;
}
}