反射JPA註解

今天無事,用反射實現了拿方法上面的jpa註解的一個小程序,以供參考

  1. package com.sinoframe.common.mdb;  
  2.  
  3. import java.lang.reflect.Field;  
  4. import java.lang.reflect.Modifier;  
  5. import java.lang.reflect.Method;  
  6.  
  7. public class BeanAnalyst {  
  8.      public static void test()  
  9.      {  
  10.       try   
  11.      {  
  12.      //加載WorkPOJO,注意這裏一定要寫全類名,包括包名,因爲包名是類名的一部分  
  13.       Class pojo = Class.forName("com.sinoframe.bean.CmPeople");  
  14.      //獲取域的數組  
  15.       Field []fieldList = pojo.getDeclaredFields();  
  16.      //獲取方法的數組  
  17.       Method []methodList = pojo.getDeclaredMethods();  
  18.  
  19.       System.out.println("WorkerPOJO類的所有字段:");  
  20.       System.out.println("修飾符" + " " + "類型" + " " + "字段名");  
  21.  
  22.       for(int i = 0;i < fieldList.length;i++)  
  23.      {  
  24.       Field field = fieldList[i];  
  25.         
  26.       boolean methodAnnotation = field.isAnnotationPresent(pojo);  
  27.      //用下面的形式獲取具體的修飾符  
  28.       if(!methodAnnotation)  
  29.          {  
  30.           continue;  
  31.          }  
  32.       System.out.println(Modifier.toString(field.getModifiers()) + " " + field.getType() + " " + field.getName());  
  33.      }  
  34.  
  35.       System.out.println();  
  36.       System.out.println("WorkerPOJO類的所有方法(僅包括annotation修飾的方法):");  
  37.  
  38.       for(int j = 0;j < methodList.length;j++)  
  39.      {  
  40.       Method method = methodList[j];  
  41.      //判斷方法是否被Annotation修飾  
  42.       boolean methodmethodAnnotation = method.isAnnotationPresent(javax.persistence.Column.class);  
  43.  
  44.      //如果被annotation修飾,則過濾掉該方法,即不輸出  
  45.       if(!methodAnnotation)  
  46.      {  
  47.       continue;  
  48.      }  
  49.      //獲取方法參數列表  
  50.       Class parameters[] = method.getParameterTypes();  
  51.  
  52.       System.out.print((method.getAnnotation(javax.persistence.Column.class)).name()+"         "+Modifier.toString(method.getModifiers()) + "    " + method.getReturnType() + " " + method.getName() + " (");  
  53.  
  54.       for(int k = 0;k < parameters.length;k++)  
  55.      {  
  56.       System.out.print(parameters[k].toString());  
  57.      }  
  58.  
  59.       System.out.println(")");  
  60.      }  
  61.      }  
  62.       catch(ClassNotFoundException exception1)  
  63.      {  
  64.       exception1.printStackTrace();  
  65.      }  
  66.  
  67.      }  
  68. }  

可以拿到方法上面的@column註解的name屬性,如果要自己測試的話,把test改成main你懂的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章