学习目标:
1、明白Java的注解的意义
2、掌握自定义注解的语法
学习过程:
一、元数据Annotation
java元数据Meta-Data(注释类型)是用于接口、类、方法以及属性的一种标注,这种注释相当于给它们添加了额外的辅助信息,可以通过反射机制编程实现对这些元数据的访问并提供相应的逻辑。如果没有外部解析工具等对其加以解析和处理的情况,本身不会对Java的源代码或class文件等产生任何影响,也不会对它们的执行产生任何影响。
二、示例代码
1、申明一个运行期元数据的语法是:
1 2 3 4 5 6 7 | @Retention (RetentionPolicy.RUNTIME) @Target (ElementType.METHOD) public @interface Myann { String name() default "刘德华" ; } |
2、使用
1 2 3 4 5 6 7 8 9 | public class Teacher { // @Deprecated @Myann (name= "刘邦" ) public void teacher(){ } } |
3、可以使用反射处理元数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | public class Run { public static void main(String[] args) throws Exception{ Class cla=Class.forName( "com.annotation.Teacher" ); //通过发射拿到所有的方法 Method [] methods= cla.getDeclaredMethods(); for (Method method:methods){ //可以拿到上面的注解 Annotation [] annotations=method.getAnnotations(); //遍历所有的注解 for (Annotation annotation:annotations){ //判断是否我写的注解 if (annotation instanceof Myann){ //强转为我的注解 Myann myann=(Myann)annotation; System.out.println(myann.name()); //以下就可以写业务需求 } } } } } |