注解(Annotation) 为我们在代码中天界信息提供了一种形式化的方法,是我们可以在稍后
某个时刻方便地使用这些数据(通过 解析注解 来使用这些数据)。
注解的语法比较简单,除了@符号的使用以外,它基本上与java的固有语法一致,java内置了三种
注解,定义在java.lang包中。
@Override 表示当前方法是覆盖父类的方法。
@Deprecated 表示当前元素是不赞成使用的。
@SuppressWarnings 表示关闭一些不当的编译器警告信息。
下面是一个定义注解的实例
Java代码
- package Test_annotation;
- 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(ElementType.METHOD)
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Inherited
- public @interface Test {
- public int id();
- public String description() default "no description";
- }
-
下面是一个使用注解 和 解析注解的实例
Java代码
- package Test_annotation;
- import java.lang.reflect.Method;
- public class Test_1 {
- @Test(id = 1, description = "hello method_1")
- public void method_1() {
- }
- @Test(id = 2)
- public void method_2() {
- }
- @Test(id = 3, description = "last method")
- public void method_3() {
- }
- public static void main(String[] args) {
- 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.id() + " , description = "
- + annotation.description() + " )");
- }
- }
- }
- }