Java的Annotation

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_32502811/article/details/84875252

Annotation


  • Annotation增加了对元数据(metadata)的支持,它是代码里的特殊标记,这些标记可以在编译、类加载、运行时被读取,并执行相应的处理.
  • Annotation就像修饰符一样被使用,可用于修饰包,类、构造器、方法、成员变量、参数、局部变量的声明,这些信息被存储在Annotation的“name = value”对中。
  • Annotation是一个接口,程序可以通过反射来获取指定程序元素的Annotation对象。

基本的Annotation

java中的java.lang包提供了三个基本的Annotation:

@Override
@Deprecated
@SuppressWarnings
  1. @Override
  2. 指定方法覆盖。可以强制一个子类必须覆盖父类的方法。
    它的作用是告诉编译器检查这个方法,并从父类查找是否包含一个被该方法重写的方法,否则就编译出错。
  3. @Deprecated
  4. 标记已过时
    用于表示某个程序元素一过时,当其他程序使用已过时的类,方法时,编译器会给出警告。
  5. @SuppressWarnings
  6. 抑制编译器警告
    @SuppressWarnings(value="unchecked")
    public class SuppressWarningsTest{
        public static void main(String[] args){
    	List myList = new ArrayList();
        }
    }
    
## 自定义Annotation
  • 使用@interface关键字
//定义Annotation
public @interface Test{}
//使用Annotation
@Test
public class MyClass{}
  • Anotation定义还可以带成员变量,成员变量在Annotation定义中以无参数方法的形式来声明。
public @interface MyTag {
    String name();
    int age();
}
public class Test{
    @Mytag(name = "xx", age = 6)
    public void info(){
	//pass
    }
}
  • 还可以为Annotation的成员变量指定初始值,关键字用default
public @interface Mytag{
    String name() default "yeeku";
    int age() default 32;
}
public class Test{
    //因为有默认值,所以这里可以不赋值
    @Mytag
    public void info(){}
}
  • 根据Annotation是否含有成员变量,可以把Annotation分为标记Annotation元数据Annotation

猜你喜欢

转载自blog.csdn.net/sinat_32502811/article/details/84875252
今日推荐