1、注解定义:
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
/*
* 元注解@Target,@Retention,@Documented,@Inherited
*
* @Target 表示该注解用于什么地方,可能的 ElemenetType 参数包括:
* ElemenetType.CONSTRUCTOR 构造器声明
* ElemenetType.FIELD 域声明(包括 enum 实例)
* ElemenetType.LOCAL_VARIABLE 局部变量声明
* ElemenetType.METHOD 方法声明
* ElemenetType.PACKAGE 包声明
* ElemenetType.PARAMETER 参数声明
* ElemenetType.TYPE 类,接口(包括注解类型)或enum声明
*
* @Retention 表示在什么级别保存该注解信息。可选的 RetentionPolicy 参数包括:
* RetentionPolicy.SOURCE 注解将被编译器丢弃
* RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃
* RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。
*
* @Documented 将此注解包含在 javadoc 中
*
* @Inherited 允许子类继承父类中的注解
*
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
/*
* 定义注解 Test
* 注解中含有两个元素 value 和 length
*/
public @interface Test {
public String value() default "0";
public int length() default 0;
}
2、注解使用
import java.lang.reflect.Field;
public class Test_1 {
/*
* 被注解的三个方法
*/
@Test(value = "methd1", length = 2)
public String method_1;
@Test(value = "method_22", length = 4)
public String method_2;
@Test(value = "method_33", length = 6)
public String method_3;
/*
* 解析注解,将Test_1类 所有被注解方法 的信息打印出来
*/
public static void main(String[] args) {
Field[] methods = Test_1.class.getDeclaredFields();
for (Field method : methods) {
/*
* 判断方法中是否有指定注解类型的注解
*/
boolean hasAnnotation = method.isAnnotationPresent(Test.class);
if (hasAnnotation) {
/*
* 根据注解类型返回方法的指定类型注解
*/
Test annotation = method.getAnnotation(Test.class);
System.out.println("Test( method = " + method.getName()
+ " , id = " + annotation.value() + " , description = "
+ annotation.length() + " )");
}
}
/*Method[] methods = Test_1.class.getDeclaredMethods();
for (Method method : methods) {
* 判断方法中是否有指定注解类型的注解
boolean hasAnnotation = method.isAnnotationPresent(Test.class);
if (hasAnnotation) {
* 根据注解类型返回方法的指定类型注解
Test annotation = method.getAnnotation(Test.class);
System.out.println("Test( method = " + method.getName()
+ " , id = " + annotation.value() + " , description = "
+ annotation.length() + " )");
}
}*/
}
}
运行时,可以读取注解信息,通过反射来获取信息,达到目标。