Java在1.5開始引入了注解,目前流行的框架都在用注解,可想而知注解的強大之處。
以下通過自定義注解來深入了解java注解。
一、創建自定義注解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
package com.sam.annotation; import java.lang.annotation.*; /** * @author sam * @since 2017/7/13 */ @Target ({ElementType.METHOD, ElementType.FIELD}) @Retention (RetentionPolicy.RUNTIME) @Inherited @Documented public @interface MyMessage { String name() default "sam" ; int num() default 0 ; String desc(); } |
說明:
@Target、@Retention、@Inherited、@Documented為元注解(meta-annotation),它們是負責注解其他注解的。
1、Target:指明注解支持的使用范圍,取值可以參考枚舉ElementType,以下:
ElementType.TYPE //類、接口、枚舉
ElementType.FIELD //屬性
ElementType.METHOD //方法
ElementType.PARAMETER //參數
ElementType.CONSTRUCTOR //構造器
ElementType.LOCAL_VARIABLE //局部變量
ElementType.ANNOTATION_TYPE //注解
ElementType.PACKAGE //包
2、Retention:指明注解保留的的時間長短,取值參考枚舉RetentionPolicy,一下:
SOURCE //源文件中保留
CLASS //class編譯時保留
RUNTIME //運行時保留
3、Inherited:指明該注解類型被自動繼承。如果一個annotation注解被@Inherited修飾,那么該注解作用于的類 的子類也會使用該annotation注解。
4、Documented:指明擁有這個注解的元素可以被javadoc此類的工具文檔化。
二、創建測試類,使用自定義注解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package com.sam.annotation; /** * @author sam * @since 2017/7/13 */ public class AnnotationTest { @MyMessage (num = 10 , desc = "參數a" ) private static int a; @MyMessage (name = "Sam test" , desc = "測試方法test" ) public void test() { System.out.println( "test" ); } } |
在該類中的屬性和方法,使用了自定義的注解,并指明了參數。
那么現在就需要解析自定義的注解。
三、解析注解
使用反射機制處理自定義注解
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
package com.sam.annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * 使用反射處理注解 * * @author sam * @since 2017/7/13 */ public class MyMessageProcessor { public static void main(String[] args) { try { //加載annotationTest.class類 Class clazz = MyMessageProcessor. class .getClassLoader().loadClass( "com.sam.annotation.AnnotationTest" ); //獲取屬性 Field[] fields = clazz.getDeclaredFields(); //遍歷屬性 for (Field field : fields) { MyMessage myMessage = field.getAnnotation(MyMessage. class ); System.out.println( "name:" + myMessage.name() + " num:" + myMessage.num() + " desc:" + myMessage.desc()); } //獲取類中的方法 Method[] methods = clazz.getMethods(); //遍歷方法 for (Method method : methods) { //判斷方法是否帶有MyMessage注解 if (method.isAnnotationPresent(MyMessage. class )) { // 獲取所有注解 method.getDeclaredAnnotations(); // 獲取MyMessage注解 MyMessage myMessage = method.getAnnotation(MyMessage. class ); System.out.println( "name:" + myMessage.name() + " num:" + myMessage.num() + " desc:" + myMessage.desc()); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } } } |
運行MyMessageProcessor 得到結果:
1
2
3
4
|
name:sam num: 10 desc:參數a name:Sam test num: 0 desc:測試方法test Process finished with exit code 0 |
具體定制注解所實現的內容,可以在MyMessageProcessor.java中進行修改。
自此,已經對java的自定義注解有簡單的了解。
以上這篇簡單談談java自定義注解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。