注解的分类
按运行机制分:
源码注解:只在源码中存在,编译后不存在
编译时注解:源码和编译后的class文件都存在(如@Override,@Deprecated,@SuppressWarnings)
运行时注解:能在程序运行时起作用(如spring的依赖注入)
按来源分:
来自JDK的注解
第三方的注解
自定义的注解
自定义注解
如下实例给出了自定义注解的基本方法
1 package com.flypie.annotations;
2
3 import java.lang.annotation.Documented;
4 import java.lang.annotation.ElementType;
5 import java.lang.annotation.Inherited;
6 import java.lang.annotation.Retention;
7 import java.lang.annotation.RetentionPolicy;
8 import java.lang.annotation.Target;
9
10 /* @Target,@Retention,@Inherited,@Documented
11 * 这四个是对注解进行注解的元注解,负责自定义的注解的属性
12 */
13 @Target({ElementType.TYPE,ElementType.METHOD}) //表示注解的作用对象,ElementType.TYPE表示类,ElementType.METHOD表示方法
14 @Retention(RetentionPolicy.RUNTIME) //表示注解的保留机制,RetentionPolicy.RUNTIME表示运行时注解
15 @Inherited //表示该注解可继承
16 @Documented //表示该注解可生成文档
17 public @interface Design {
18 String author(); //注解成员,如果注解只有一个成员,则成员名必须为value(),成员类型只能为原始类型
19 int data() default 0; //注解成员,默认值为0
20 }
21
使用注解
1 package com.flypie;
2
3 import com.flypie.annotations.Design;
4
5 @Design(author="flypie",data=100) //使用自定义注解,有默认值的成员可以不用赋值,其余成员都要复值
6 public class Person {
7 @Design(author="flypie",data=90)
8 public void live(){
9
10 }
11 }
解析java注解
1 package com.flypie;
2
3 import java.lang.annotation.Annotation;
4 import java.lang.reflect.Method;
5
6 import com.flypie.annotations.Design;
7
8 public class Main {
9
10 public static void main(String[] args) throws ClassNotFoundException {
11
12 Class c=Class.forName("com.flypie.Person"); //使用类加载器加载类
13
14 //1、找到类上的注解
15 if(c.isAnnotationPresent(Design.class)){ //判断类是否被指定注解注解
16 Design d=(Design) c.getAnnotation(Design.class); //拿到类上的指定注解实例
17 System.out.println(d.data());
18 }
19
20 //2、找到方法上的注解
21 Method[] ms=c.getMethods();
22 for(Method m:ms){
23 if(m.isAnnotationPresent(Design.class)){ //判断方法是否被指定注解注解
24 Design d=m.getAnnotation(Design.class); //拿到类上的指定注解实例
25 System.out.println(d.data());
26 }
27 }
28
29 //3、另外一种方法
30 for(Method m:ms){
31 Annotation[] as=m.getAnnotations(); //拿到类上的注解集合
32 for(Annotation a:as){
33 if(a instanceof Design){ //判断指定注解
34 Design d=(Design) a;
35 System.out.println(d.data());
36 }
37 }
38 }
39 }
40
41 }
原文出处
flypie, Java注解入门, https://www.cnblogs.com/flypie/p/5134752.html