今天無事,用反射實現了拿方法上面的jpa註解的一個小程序,以供參考
- package com.sinoframe.common.mdb;
- import java.lang.reflect.Field;
- import java.lang.reflect.Modifier;
- import java.lang.reflect.Method;
- public class BeanAnalyst {
- public static void test()
- {
- try
- {
- //加載WorkPOJO,注意這裏一定要寫全類名,包括包名,因爲包名是類名的一部分
- Class pojo = Class.forName("com.sinoframe.bean.CmPeople");
- //獲取域的數組
- Field []fieldList = pojo.getDeclaredFields();
- //獲取方法的數組
- Method []methodList = pojo.getDeclaredMethods();
- System.out.println("WorkerPOJO類的所有字段:");
- System.out.println("修飾符" + " " + "類型" + " " + "字段名");
- for(int i = 0;i < fieldList.length;i++)
- {
- Field field = fieldList[i];
- boolean methodAnnotation = field.isAnnotationPresent(pojo);
- //用下面的形式獲取具體的修飾符
- if(!methodAnnotation)
- {
- continue;
- }
- System.out.println(Modifier.toString(field.getModifiers()) + " " + field.getType() + " " + field.getName());
- }
- System.out.println();
- System.out.println("WorkerPOJO類的所有方法(僅包括annotation修飾的方法):");
- for(int j = 0;j < methodList.length;j++)
- {
- Method method = methodList[j];
- //判斷方法是否被Annotation修飾
- boolean methodmethodAnnotation = method.isAnnotationPresent(javax.persistence.Column.class);
- //如果被annotation修飾,則過濾掉該方法,即不輸出
- if(!methodAnnotation)
- {
- continue;
- }
- //獲取方法參數列表
- Class parameters[] = method.getParameterTypes();
- System.out.print((method.getAnnotation(javax.persistence.Column.class)).name()+" "+Modifier.toString(method.getModifiers()) + " " + method.getReturnType() + " " + method.getName() + " (");
- for(int k = 0;k < parameters.length;k++)
- {
- System.out.print(parameters[k].toString());
- }
- System.out.println(")");
- }
- }
- catch(ClassNotFoundException exception1)
- {
- exception1.printStackTrace();
- }
- }
- }
可以拿到方法上面的@column註解的name屬性,如果要自己測試的話,把test改成main你懂的。