1、创建注解;(至于Retention,Target,Documented的含义自行学习)
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME) // VM将在运行期保留注释,因此可以通过反射机制读取注解的信息
@Target(ElementType.TYPE) // 表示注解类型,TYPE为类,接口,枚举的声明
@Documented // 表示此注解将包含在javadoc中
public @interface TypeAnnotation {
/** 类名 */
String ClassName();
/** 描述 */
String Description();
/** 作者 */
String author();
/** 创建日期 */
String date();
}2、测试类及方法;
import com.annotation.TypeAnnotation;
@TypeAnnotation (ClassName="AnnotationTest", Description = "测试自定义类注解", author = "rencht", date = "2013-4-8 上午10:07:54")
public class AnnotationTest {
public static void main(String[] args) throws Exception {
AnnotationTest test = new AnnotationTest();
TypeAnnotation annotation = test.getClass().getAnnotation(TypeAnnotation.class);
System.out.println(annotation.ClassName());
System.out.println(annotation.Description());
System.out.println(annotation.author());
System.out.println(annotation.date());
}
}3、输出结果;
AnnotationTest
测试自定义类注解
rencht
2013-4-8 上午10:07:54Tips:
1、由于使用反射机制取得注解,注解类型为局部变量LOCAL_VARIABLE时无法取得,那该类型注解的意义何在?
1067

被折叠的 条评论
为什么被折叠?



