注解,java中提供了一种原程序中的元素关联任何信息、任何元素的途径的途径和方法。java
注解是那些插入到源代码中使用其余工具能够对其进行处理的标签。注解不会改变程序的编译方式。java编译器会对包含注解与不包含注解的代码生成相同的虚拟机指令。在java中,注解是被当作修饰符(如public/static之类)来使用的。程序员
注释是供人看的,注解是供程序调用的。一种是程序员写给另外一个程序员的,一种是程序员写给计算机解析的。ide
给注解进行注解,用于自定义注解。工具
//@Target(ElementType.METHOD) @Target({ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface Description { String desc() default ""; String author() default ""; int age() default 18; }
原始类型、String、Class、Annotation、Enumeration
;// @<注解名称>(<成员名1>=<成员值1>,<成员名2>=<成员值2> ...) @Description(desc = "I'm class annotation") public class AnnotationApp { @Description(desc = "I'm method annotation",author = "rudy") public String eyeColor(){ return "red"; } }
经过反射获取类、方法、成员上的运行时
注解信息,从而实现动态控制程序运行的逻辑。.net
import Annotation.Description; import org.junit.Test; public class AnnotationTest { @Test public void testParse() throws ClassNotFoundException { // 取出注解 Class cls = Class.forName("Annotation.AnnotationApp"); boolean isExit = cls.isAnnotationPresent(Description.class); if(isExit){ // 作逻辑处理 Description annotation = (Description) cls.getAnnotation(Description.class); System.out.println("get annotation:" + annotation.desc()); }else{ System.out.println("no annotation!"); } } }