JAVA 注解示例 详解
Java 2010-08-25 16:53:19 阅读2 评论0 字号:大中小 订阅
某个时刻方便地使用这些数据(通过 解析注解 来使用这些数据)。
注解的语法比较简单,除了@符号的使用以外,它基本上与java的固有语法一致,java内置了三种
注解,定义在java.lang包中。
@Override 表示当前方法是覆盖父类的方法。
@Deprecated 表示当前元素是不赞成使用的。
@SuppressWarnings 表示关闭一些不当的编译器警告信息。
下面是一个定义注解的实例
package com.proxy.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;
/*
* 元注解@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.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Demo {
public int id();
public String descriiption() default "no description";
}
TestDemo.java
package com.proxy.annotation;
import java.lang.reflect.Method;
/**
* 测试注解
*
*/
public class TestDemo {
/**
* 注解三个方法
*/
@Demo(id = 1,descriiption = "hello method_1")
public void method_1(){
}
@Demo(id = 1)
public void method_2(){
}
@Demo(id = 3,descriiption = "last meth")
public void method_3(){
}
/*
* 解析注解,将本类,所有被注解的方法,找出来
*/
public static void main(String[] args){
Method[] methods = TestDemo.class.getDeclaredMethods();
for(Method method:methods){
/*
* 判断方法中是否有指定注解类型的注解
*/
boolean hasAnnotation = method.isAnnotationPresent(Demo.class);
if(hasAnnotation){
/*
* 根据注解类型返回方法的指定类型注解
*/
Demo annotation = method.getAnnotation(Demo.class);
System.out.println("Demo(method = " + method.getName()
+ " , id = " + annotation.id() + " ,description = "
+ annotation.descriiption());
}
}
}
}