今天无事,用反射实现了拿方法上面的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你懂的。