注解
叫元数据,一种代码级别的说明,它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举在同一个层次,它可以声明在包、类、字段、局部变量、方法参数等的前面,用来对这些元素进行说明、注释。
注解的作用分类
注解按照运行机制分类
(1)注解:用于描述代码,说明程序,主要目的是为了给计算机看,且能够影响程序的运行。
(2)注释:用于描述代码的作用和一些关键性的知识点,使用文字描述程序,是为了给程序员观看,以此来使程序员能够以最快的时间了解被注释的代码。
元注解:用于描述注解的注解,在创建注解时使用
1. @Target属性值:
2.@Retention属性值:
3.@Documented:该注解的作用就是表示此注解标记的注解可以包含到javadoc文件中去
4.@Inherited:描述注解是否能够被子类所继承
1.格式:
@Inherited//元注解public @interface zhujie{}
2.注解本质:注解的本质上就是一个接口,该接口默认继承Annotation
public interface MyAnno extends java.lang.annotation.Annotion
3.属性:接口中可以定义的内容(成员方法、抽象方法)
属性的返回值:
属性赋值注意事项
自定义注解annotation
@Retention(value = RetentionPolicy.RUNTIME) @Target(value = ElementType.TYPE) public @interface annotation { String name() default "木鱼"; int age(); int[] score(); }
使用以上注解的类TestAnnotation
//name具有默认值,不需要必须为name赋值,但也可以重新赋值 @annotation(age=20,score={99,100,100}) public class TestAnnotation { public static void main(String[] args) throws ClassNotFoundException { Class clazz = Class.forName("test.TestAnnotation"); annotation annotation = (annotation) clazz.getAnnotation(annotation.class); System.out.println("姓名:"+annotation.name()+" 年龄:"+annotation.age()); System.out.print("成绩为:"); int[] score=annotation.score(); for (int score1:score){ System.out.print(score1+" "); } } }
运行结果
两个方法:
isAnnotationPresent(Class<? extends Annotation> annotationClass)
判断是否应用了某个注解1.创建自定义注解
@Retention(value = RetentionPolicy.RUNTIME) @Target(value = ElementType.FIELD) public @interface StringNull { }
2.创建实体类
public class Student { @StringNull public String name=null; @StringNull public String xuehao=null; @StringNull public String sex=null; public void setName(String name) { this.name = name; } public void setXuehao(String xuehao) { this.xuehao = xuehao; } public void setSex(String sex) { this.sex = sex; } }
3.创建测试类,测试注解
public class TestAnnotation { public static void main(String[] args) throws Exception{ Class clazz = Class.forName("test.Student"); Student student =(Student) clazz.newInstance(); student.setName("小明"); Field[] fields= clazz.getFields(); for(Field f:fields){ if(f.isAnnotationPresent(StringNull.class)){ if(f.get(student)==null){ System.out.println(f.getName()+":是空的字符串属性"); }else{ System.out.println(f.getName()+":"+f.get(student)); } } } } }
4.运行结果