标签:blog io ar os 使用 sp java for strong
使用一种对代码级别的说明,在JDK5.0引入支持的新特性,与类、接口、枚举同属一个层次。声明使用在包、类、字段、方法、局部变量、方法参数等前面,对这些元素进行说明注释。可以作为编译检查、生成说明文档、代码分析等功能。
阻止编译器发出的某些警告信息标记某个过时的类或方法标记重写父类的方法@Retention
标记该注解的声明周期,具有如下参数:
RetentionPolicy.SOURCE:指定注解只保留在一个源文件中RetentionPolicy.CLASS:指定注解只保留在一个class文件中(默认值)RetentionPolicy.RUNTIME:指定注解可以保留在程序运行期间@Target
标记该注解可以被声明在哪些元素前,具有如下参数:
ElementType.TYPE:该注解只能被声明在一个类前ElementType.FIELD:该注解只能被声明在一个类的字段前ElementType.METHOD:该注解只能被声明在一个类的方法前ElementType.PARAMETER:该注解只能被声明在一个方法参数前ElementType.CONSTRUCTOR:该注解只能声明在一个类的构造方法前ElementType.LOCAL_VARIABLE:该注解只能声明在一个局部变量前ElementType.ANNOTATION_TYPE:该注解只能声明在一个注解类型前ElementType.PACKAGE:该注解只能声明在一个包名前@Document
标记该注解可以被javadoc工具提取成文档。
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTag {
//定义字段,并指定默认值
String name() default "java";
int age() ;
}
默认情况下,注解可以修饰任何程序元素,包括类、接口、方法等。
@MyTag(age =10)
public class AnnotationTest {
}
未赋默认值的字段,使用注解必须赋值。
通过java.lang.reflect包下的AnnotatedElement,获取注解的程序元素,主要有如下实现类:Class、Constructor、Field、Method、Package。
AnnotatedElement接口主要提供以下方法获取注解信息:
- getAnnotation(Class<Annotation> annotationClass):获取指定注解,不存在则返回null
- getAnnotations():获取程序元素上存在的所有注解
- isAnnotationPresent(Class<? extends Annotation> annotationClass):判断该元素是否存在指定注解
import java.lang.annotation.Annotation;
public class Main {
public static void main(String[] args) {
AnnotationTest test = new AnnotationTest();
Annotation[] annotations = test.getClass().getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation.toString());
}
}
}
输出结果:@com.annotation.MyTag(name=java, age=10)
标签:blog io ar os 使用 sp java for strong
原文地址:http://www.cnblogs.com/bennyyuan/p/4118758.html