自定義 Java Annotation ,讀取註解值
阿新 • • 發佈:2017-08-23
sta tools stp exc num value mage test lang
1. 首先是自定義註解:
Java代碼- package cn.veji.hibernate.po;
- 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 Privilege {
- String[] value();
- }
2.定義使用註解類:
- package cn.veji.hibernate.po;
- package cn.veji.hibernate.po;
- public class TestPrivilege {
- @Privilege( { "a" })
- public void a() {
- }
- @Privilege( { "b" })
- public void b() {
- }
- @Privilege( { "c" })
- public void c() {
- }
- }
3.讀取註解值幫助類:
- package cn.veji.hibernate.po;
- package cn.veji.hibernate.test;
- import java.lang.annotation.Annotation;
- import java.lang.reflect.Method;
- import java.util.HashMap;
- import java.util.Map;
- import cn.veji.hibernate.po.Privilege;
- import cn.veji.hibernate.po.TestPrivilege;
- public class AnnotationUtil {
- public static AnnotationUtil anno = null;
- public static AnnotationUtil getInstance() {
- if (anno == null) {
- anno = new AnnotationUtil();
- }
- return anno;
- }
- /**
- * 讀取註解值
- *
- * @param annotationClasss 處理Annotation類名稱
- * @param annotationField 處理Annotation類屬性名稱
- * @param className 處理Annotation的使用類名稱
- * @return
- * @throws Exception
- */
- @SuppressWarnings("all")
- public Map<String, String> loadVlaue(Class annotationClasss,
- String annotationField, String className) throws Exception {
- System.out.println("處理Annotation類名稱 === "+annotationClasss.getName());
- System.out.println("處理Annotation類屬性名稱 === "+annotationField);
- System.out.println("處理Annotation的調用類名稱 === "+className);
- Map<String, String> map = new HashMap<String, String>();
- Method[] methods = Class.forName(className).getDeclaredMethods();
- for (Method method : methods) {
- if (method.isAnnotationPresent(annotationClasss)) {
- Annotation p = method.getAnnotation(annotationClasss);
- Method m = p.getClass()
- .getDeclaredMethod(annotationField, null);
- String[] values = (String[]) m.invoke(p, null);
- for (String key : values) {
- System.out.println("註解值 === " + key);
- map.put(key, key);
- }
- }
- }
- System.out.println("map數量 === " + map.size());
- return map;
- }
- public static void main(String[] args) throws Exception {
- AnnotationUtil.getInstance().loadVlaue(Privilege.class, "value",
- TestPrivilege.class.getName());
- }
- }
4.執行結果:
- 處理Annotation類名稱 === cn.veji.hibernate.po.Privilege
- 處理Annotation類屬性名稱 === value
- 處理Annotation的調用類名稱 === cn.veji.hibernate.po.TestPrivilege
- 註解值 === c
- 註解值 === a
- 註解值 === b
- map數量 === 3
自定義 Java Annotation ,讀取註解值