开始接触java注解的时候,感觉是个很高深的概念,经过一段时间的学习,对注解有了新的认识,并没有想象的那么复杂。
注解本质上就是一个标记,是给程序看的。
如果自定义了一个注解,但是没有对自定义的注解做任何解析,那么这个自定义注解完全没有任何作用,就像一个注释一样(但是注释主要是给人看的)。
注解的存在主要是在一定程度上替换.XML配置文件(所以在使用注解的时候,注解中定义的值必须是一个常量)。
package annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Information { String sex() default "female"; Details[] details(); }
package annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Details { String details(); }
package annotations; public interface Person { void getInformation(String information); }
package annotations; public class Student implements Person { @Override @Information(sex = "male", details = { @Details(details = "i am a student"), @Details(details = "i am a dancer") } ) public void getInformation(String information) { System.out.println(information); } }
package annotations; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; public class AnnotationTest { public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException { Map<String, Map<String, Object>> AnnotaionsInAllMethodMap = new HashMap<>(); Class<?> clazz = Class.forName("annotations.Student"); Student student=(Student) clazz.newInstance(); Method[] methods = clazz.getDeclaredMethods(); for(Method method:methods){ Map<String, Object> AnnotaionsInOneMethodMap = new HashMap<>(); if (method.isAnnotationPresent(Information.class)) { Information information = method.getAnnotation(Information.class); String sex=information.sex(); AnnotaionsInOneMethodMap.put("sex", sex); Details[] details=information.details(); StringBuilder mergeDetails=new StringBuilder(); for(Details detail:details){ mergeDetails = mergeDetails.append(detail.details()); } AnnotaionsInOneMethodMap.put("Details", mergeDetails.toString()); method.invoke(student, AnnotaionsInOneMethodMap.toString()); } AnnotaionsInAllMethodMap.put(method.getName(), AnnotaionsInOneMethodMap); } } }
public @interface Information :注解本质上相当于一个借口,只不过是一个继承了Annotation的接口
Information information = method.getAnnotation(Information.class); 通过动态代理,生成了一个实现@interface Information 特殊接口的代理实例