JDK1.5引入的注解基本用法

一、java提供的基本注解java

@SuppressWarnings,数组

@SuppressWarnings("deprecation")告诉编译器忽略过期提醒ide

@Deprecated 标识某个方法过期了函数

@Override覆盖某个方法生命周期

二、自定义注解及应用get

定义一个注解:编译器

@Retention(RetentionPolicy.RUNTIME)//表示注解的生命周期都运行时,还有source,class两个类型
@Target({ElementType.METHOD,ElementType.TYPE})//表示注解能够用在什么类型上面
public @interface MyAnnotation {//注解的声明
 String color() default "green";//注解的常量color,默认值为green
 int[] vaule() default {1,2,3};//注解的常量vaule,默认值为数组{1,2,3}io

}
编译

应用自定义注解:class

@MyAnnotation(vaule={1,2,3},color="red")//赋值的时候color看成变量来使用,若是是value是能够省略变量名称的({1,2,3})
public class AnnotationTest {

 public static void main(String[] args) {
  if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)){
   MyAnnotation myAnnotation =AnnotationTest.class.getAnnotation(MyAnnotation.class);
   System.out.println(myAnnotation);

 System.out.println(myAnnotation.color());//调用的时候能够像函数同样使用
   System.out.println(myAnnotation.value());  }

 }

}

相关文章
相关标签/搜索