注解
来源:互联网 发布:js检验只能输入数字 编辑:程序博客网 时间:2024/06/16 21:46
java源文件---》class文件---》类加载器加载,解析成内存中的字节码
一:定义注解类
@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD,ElementType.TYPE})public @interface ItcastAnnotation {String color() default "blue";String value();int[] arrayAttr() default {3,4,4};EnumTest.TrafficLamp lamp() default EnumTest.TrafficLamp.RED;MetaAnnotation annotationAttr() default @MetaAnnotation("lhm");}
二:应用并测试
@ItcastAnnotation("xyz")public static void main(String[] args) throws Exception{// TODO Auto-generated method stub//System.runFinalizersOnExit(true);if(AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class)){ItcastAnnotation annotation = (ItcastAnnotation)AnnotationTest.class.getAnnotation(ItcastAnnotation.class);System.out.println(annotation.color());System.out.println(annotation.value());System.out.println(annotation.arrayAttr().length);System.out.println(annotation.lamp().nextLamp().name());System.out.println(annotation.annotationAttr().value());}Method mainMethod = AnnotationTest.class.getMethod("main", String[].class);ItcastAnnotation annotation2 = (ItcastAnnotation)mainMethod.getAnnotation(ItcastAnnotation.class);System.out.println(annotation2.value());}
值:
red
abc
1
GREEN
flx
xyz
0 0