1、註解基本知識java
一、元註解數組
元註解是指註解的註解。包括 @Retention @Target @Document @Inherited四種。session
1. Annotation型定義爲@interface, 全部的Annotation會自動繼承java.lang.Annotation這一接口,而且不能再去繼承別的類或是接口.函數
2. 參數成員只能用public或默認(default)這兩個訪問權修飾post
3. 參數成員只能用基本類型byte,short,char,int,long,float,double,boolean八種基本數據類型和String、Enum、Class、annotations等數據類型,以及這一些類型的數組.測試
4. 要獲取類方法和字段的註解信息,必須經過Java的反射技術來獲取 Annotation對象,由於你除此以外沒有別的獲取註解對象的方法this
5. 註解也能夠沒有定義成員, 不過這樣註解就沒啥用了spa
自定義註解類時, 能夠指定目標 (類、方法、字段, 構造函數等) , 註解的生命週期(運行時,class文件或者源碼中有效), 是否將註解包含在javadoc中及是否容許子類繼承父類中的註解, 具體以下:.net
1. @Target 表示該註解目標,可能的 ElemenetType 參數包括:code
ElemenetType.CONSTRUCTOR 構造器聲明
ElemenetType.FIELD 域聲明(包括 enum 實例)
ElemenetType.LOCAL_VARIABLE 局部變量聲明
ElemenetType.METHOD 方法聲明
ElemenetType.PACKAGE 包聲明
ElemenetType.PARAMETER 參數聲明
ElemenetType.TYPE 類,接口(包括註解類型)或enum聲明
2. @Retention 表示該註解的生命週期,可選的 RetentionPolicy 參數包括
RetentionPolicy.SOURCE 註解將被編譯器丟棄
RetentionPolicy.CLASS 註解在class文件中可用,但會被VM丟棄
RetentionPolicy.RUNTIME VM將在運行期也保留註釋,所以能夠經過反射機制讀取註解的信息
3. @Documented 指示將此註解包含在 javadoc 中
4. @Inherited 指示容許子類繼承父類中的註解
2、在java中如何使用
2.一、定義註解
package com.test.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; public class MyAnnotation { /** * 註解類 * @author T4980D * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface MyClassAnnotation { String uri(); String desc(); } /** * 構造方法註解 * @author T4980D * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.CONSTRUCTOR) public @interface MyConstructorAnnotation { String uri(); String desc(); } /** * 個人方法註解 * @author Owner * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyMethodAnnotation { String uri(); String desc(); } /** * 字段註解定義 * @author Owner * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface MyFieldAnnotation { String uri(); String desc(); } /** * * 能夠同時應用到類上和方法上 * @author T4980D * */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface Yts { // 定義枚舉 public enum YtsType { util, entity, service, model } // 設置默認值 public YtsType classType() default YtsType.util; // 數組 int[] arr() default {3, 7, 5}; String color() default "blue"; } }
2.二、基本測試註解
package com.test.annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import com.test.annotation.MyAnnotation.MyClassAnnotation; import com.test.annotation.MyAnnotation.MyConstructorAnnotation; import com.test.annotation.MyAnnotation.MyFieldAnnotation; import com.test.annotation.MyAnnotation.MyMethodAnnotation; import com.test.annotation.MyAnnotation.Yts; import com.test.annotation.MyAnnotation.Yts.YtsType; @MyClassAnnotation(desc = "The class", uri = "com.test.annotation.Test") @Yts(classType =YtsType.util) public class TestAnnotation { @MyFieldAnnotation(desc = "The class field", uri = "com.test.annotation.Test#id") private String id; @MyConstructorAnnotation(desc = "The class constructor", uri = "com.test.annotation.Test#MySample") public TestAnnotation() { } public String getId() { return id; } @MyMethodAnnotation(desc = "The class method", uri = "com.test.annotation.Test#setId") public void setId(String id) { System.out.println(" method info: "+id); this.id = id; } @MyMethodAnnotation(desc = "The class method sayHello", uri = "com.test.annotation.Test#sayHello") @Yts public void sayHello(String name){ if(name == null || name.equals("")){ System.out.println("hello world!"); }else{ System.out.println(name + "\t:say hello world!"); } } public static void main(String[] args) throws Exception { Class<TestAnnotation> clazz = TestAnnotation.class; // 獲得類註解 MyClassAnnotation myClassAnnotation = clazz.getAnnotation(MyClassAnnotation.class); System.out.println(myClassAnnotation.desc() + " "+ myClassAnnotation.uri()); // 獲得構造方法註解 Constructor<TestAnnotation> cons = clazz.getConstructor(new Class[]{}); MyConstructorAnnotation myConstructorAnnotation = cons.getAnnotation(MyConstructorAnnotation.class); System.out.println(myConstructorAnnotation.desc() + " "+ myConstructorAnnotation.uri()); // 獲取方法註解 Method method = clazz.getMethod("setId", new Class[]{int.class}); MyMethodAnnotation myMethodAnnotation = method.getAnnotation(MyMethodAnnotation.class); System.out.println(myMethodAnnotation.desc() + " "+ myMethodAnnotation.uri()); // 獲取字段註解 Field field = clazz.getDeclaredField("id"); MyFieldAnnotation myFieldAnnotation = field.getAnnotation(MyFieldAnnotation.class); System.out.println(myFieldAnnotation.desc() + " "+ myFieldAnnotation.uri()); } }
2.三、經過反射解析
package com.test.annotation; import java.lang.reflect.Method; import java.util.Arrays; import com.test.annotation.MyAnnotation.MyClassAnnotation; import com.test.annotation.MyAnnotation.MyMethodAnnotation; import com.test.annotation.MyAnnotation.Yts; import com.test.annotation.MyAnnotation.Yts.YtsType; public class ParseAnnotation { /** * 解析方法註解 * @param <T> * @param clazz */ public static <T> void parseMethod(Class<T> clazz) { try { T obj = clazz.newInstance(); for (Method method : clazz.getDeclaredMethods()) { MyMethodAnnotation methodAnnotation = method.getAnnotation(MyMethodAnnotation.class); if (methodAnnotation!=null) { //經過反射調用帶有此註解的方法 method.invoke(obj, methodAnnotation.uri()); } Yts yts = (Yts) method.getAnnotation(Yts.class); if (yts != null) { if (YtsType.util.equals(yts.classType())) { System.out.println("this is a util method"); } else { System.out.println("this is a other method"); } System.out.println(Arrays.toString(yts.arr())); //打印數組 System.out.println(yts.color()); //輸出顏色 } System.out.println("\t\t-----------------------"); } } catch (Exception e) { e.printStackTrace(); } } /** * 解析類註解 * @param <T> * @param clazz */ public static <T> void parseType(Class<T> clazz) { try { Yts yts = (Yts) clazz.getAnnotation(Yts.class); if (yts != null) { if (YtsType.util.equals(yts.classType())) { System.out.println("this is a util class"); } else { System.out.println("this is a other class"); } } MyClassAnnotation classAnnotation = (MyClassAnnotation) clazz.getAnnotation(MyClassAnnotation.class); if (classAnnotation != null) { System.err.println(" class info: "+classAnnotation.uri()); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { parseMethod(TestAnnotation.class); parseType(TestAnnotation.class); } }
3、註解應用案例
3.一、關於細粒度權限攔截的問題,在Struts2中能夠根據登陸用戶所具備的的權限進行任一一個action方法的攔截,能夠定義一個自定義方法註解,例如
@Retention(RetentionPolicy.RUNTIME)//表明Permission註解保留在的階段 @Target(ElementType.METHOD)//標註在方法上面 public @interface Permission { /** 模塊 */ String module(); /** 權限值 */ String privilege(); }
三、2 好比有一個部門action,Department.action,有一個方法public String departmentlistUI(){}能夠這樣定義方法
@Permission(module="department",privilege="view") public String departmentlistUI(){ }
3.三、而後自定定義一個權限攔截器PrivilegeInterceptor.java並在struts.xml中註冊,在實現interceptor接口後,實現方法public String intercept(ActionInvocation invocation) throws Exception {},在這裏調用任一個action方法都會通過該攔截方法,經過invocation能夠獲取當前調用的action的名字,以及調用的action的哪一個方法,經過這段代碼能夠獲取action名字和方法名。
String actionName=invocation.getProxy().getActionName(); String methodName=invocation.getProxy().getMethod(); System.out.println("攔截到:action的名字:"+actionName+"方法名:"+methodName);
四、而後經過反射技術,獲取該方法上的自定義權限註解,獲取當前登陸的用戶(從session中),遍歷當前用戶的所擁有的權限組,而且遍歷任一個權限組下的全部的權限,看是否包括該方法上註解所需的權限。這樣就能夠完成細粒度的action方法權限攔截了。
private boolean validate(ActionInvocation invocation) throws SecurityException, NoSuchMethodException { String methodName=invocation.getProxy().getMethod(); Method currentMethod = invocation.getAction().getClass().getMethod(methodName); if(currentMethod != null && currentMethod.isAnnotationPresent(Permission.class)){ //獲得方法上的註解 Permission permission = currentMethod.getAnnotation(Permission.class); //該方法上的所須要的權限 SystemPrivilege methodPrivilege = new SystemPrivilege(new SystemPrivilegePK(permission.module(), permission.privilege())); //獲得當前登陸的用戶 Employee e = (Employee) ActionContext.getContext().getSession().get("loginUser"); //遍歷當前用戶下的全部的權限組 for(PrivilegeGroup group : e.getGroups()){ //若是該權限組下包含,要訪問該方法所須要的權限,就放行 if(group.getPrivileges().contains(methodPrivilege)){ return true; } } //說明遍歷的該用戶全部的權限組,沒有發現該權限,說明沒有該權限 return false; } //沒有標註註解,表示誰均可以調用該方法 return true; }