本帖最后由 王春晓 于 2013-5-19 18:36 编辑
- <p>import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;</p><p>import cn.itcast.day1.EnumTest;</p><p>
- @Retention(RetentionPolicy.RUNTIME)//元注解-->保留注解至运行时期
- @Target({ElementType.METHOD,ElementType.TYPE})
- public @interface ItcastAnnotation {
- String color() default "bule";//指定一个缺省值
- String value();
- int[] arrayAttr() default {3,4,5};
- EnumTest.TrafficLamp lamp() default EnumTest.TrafficLamp.RED;
- MetaAnnotation annotationAttr() default @MetaAnnotation("mmm");
- Class a() default String.class;
- }
- @ItcastAnnotation(color = "red",value = "abc",arrayAttr = {1,2,3},annotationAttr=@MetaAnnotation("flx"))//只要一个值的话可以不写color= value=
- public class AnnutationTest {
- @SuppressWarnings("deprecation")
- @ItcastAnnotation("xyz")
- public static void main(String[] args){
- System.runFinalizersOnExit(true);
- if(AnnutationTest.class.isAnnotationPresent(ItcastAnnotation.class)){
- ItcastAnnotation annutation = (ItcastAnnotation)AnnutationTest.class.getAnnotation(ItcastAnnotation.class);
- System.out.println(annutation.color());
- System.out.println(annutation.value());
- System.out.println(annutation.arrayAttr().length);
- System.out.println(annutation.lamp().nextLamp().name());
- System.out.println(annutation.annotationAttr().value());
- System.out.println(annutation.a());
- }
- }
- @Deprecated
- public static void sayHello(){
- System.out.println("hello");
- }
- }
- </p><div class="quote"><blockquote>张孝祥老师的高新技术里面讲解了注解的用法,但是讲了这么多用法,什么时候才应该用到注解呢?
复制代码 |