JAVA反射與註解實例

1    JAVA反射機制


JAVA反射機制是在運行狀況中,號碼大全關於恣意一個類,關鍵詞挖掘工具都能夠曉得這個類的一切特點和辦法;關於恣意一個目標,都能夠調用它的恣意一個辦法和特點;這種動態獲取的信息以及動態調用目標的辦法的功能稱爲java言語的反射機制。或許說,JAVA反射機制指的是咱們能夠於運行時加載、探知、運用編譯時間完全不知道的classes。換句話說,Java程序能夠加載一個運行時才得知稱號的class,得悉其完好結構(但不包括methods界說),並生成其目標實體、或對其fields設值、或引發其methods。

2       JAVA 註解

Annotation(註解)是JDK5.0及今後版本引入的。它能夠用於創建文檔,盯梢代碼中的依賴性,甚至履行基本編譯時查看。註解是以‘@註解名’在代碼中存在的,依據註解參數的個數,咱們能夠將註解分爲:符號註解、單值註解、完好註解三類。它們都不會直接影響到程序的語義,僅僅作爲註解(標識)存在,咱們能夠通過反射機制編程完成對這些元數據(用來描繪數據的數據)的拜訪。別的,你能夠在編譯時挑選代碼裏的註解是否只存在於源代碼級,或許它也能在class文件、或許運行時中呈現(SOURCE/CLASS/RUNTIME)。

3       註解BEAN


自界說註解類,如下:

@Retention(RetentionPolicy.RUNTIME)

public @interface PropertyInfoAnnotation {

       public String code();   // 代碼

       public String name(); // 稱號

       public long orderNo();// 排序順序號

};

簡略JAVA BEAN如下:

public class BaseMeasureData {

       @PropertyNameAnnotation(code="IN",name="目標代碼",orderNo=1)

    private String iN;

       @PropertyNameAnnotation(code="DN",name="維度",orderNo=2)

       private String dN;

       @PropertyNameAnnotation(code="VV",name="數據值",orderNo=3)

    private String vV;

    public String getIN() {

              return iN;

       }

       public void setiN(String iN) {

              this.iN = iN;

       }

       public String getDN() {

              return dN;

       }

       public void setdN(String dN) {

              this.dN = dN;

       }

       public String getVV() {

              return vV;

indexRead arguments from command-line "http://www.shoudashou.com"

       }-        indexRead arguments from command-line "http://www.4lunwen.cn"

-        indexRead arguments from command-line "http://www.zx1234.cn"

-        indexRead arguments from command-line "http://www.penbar.cn"

-        indexRead arguments from command-line "http://www.whathappy.cn"

-        indexRead arguments from command-line "http://www.lunjin.net"

-        indexRead arguments from command-line "http://www.ssstyle.cn"

-        indexRead arguments from command-line "http://www.91fish.cn"

-        indexRead arguments from command-line "http://www.fanselang.com"

       public void setvV(String vV) {

              this.vV = vV;

       }

4       註釋協助類


註釋管理器,作爲拜訪註釋信息的入口,如下:

public class PropertyHelper {

       // 用於禁止在類外部用結構函數實例化該類。

       private PropertyHelper() {

             

       }

       private static PropertyHelper instance=new PropertyHelper();

       public static PropertyHelper getInstance(){

              return instance;

       }

       private Map> beanCachePropertyCodeMap=new HashMap>();

      

       /**

        * 獲取特點代碼及排序順序號。

        * @param bean

        * @return

        */

       public Map getBeanPropertyCode(Object bean){

              Map result=null;

              result=(Map)this.beanCachePropertyCodeMap.get(bean.getClass());

              if(result!=null)

                     return result;

              else{

                     result=this.propertyCodeParse(bean);

                     this.beanCachePropertyCodeMap.put(bean.getClass(), result);

              }

              return result;

       }

       /**

        * 將類的特點代碼及排序順序號保存到內存目標。

        * @param bean

        * @return

        */

       private Map propertyCodeParse(Object bean){

              Map result=null;

              if(bean==null)

                     return null;

              Field[] fields=bean.getClass().getDeclaredFields();

              if ( fields == null) {

                     return null;

              }

              result=new HashMap(fields.length);

              for (Field field : fields) {

                     if (field.isAnnotationPresent(PropertyNameAnnotation.class)) {

                            PropertyNameAnnotation annotation=field.getAnnotation(PropertyNameAnnotation.class);

                            result.put(annotation.code(), Long.valueOf(annotation.orderNo()));

                     }

              }

              return result;

       }

       /**

        * 獲取排序的特點代碼。

        * @return

        */

       public String[] getOrderedCode(Object bean) {

              final Map map = getInstance().getBeanPropertyCode(bean);

              Setset = map.keySet();

              String [] result = set.toArray(new String[set.size()]);

              Arrays.sort(result, new Comparator(){

                     public int compare(Object o1, Object o2) {

                            return map.get(o1).compareTo(map.get(o2));

                     }

              });

              return (String[])result;

       }

};

5       反射與註釋使用


private void getObjPro(Object obj, Map dataMap, String className) {

   Class clas; 

   if (obj == null) { 

      clas = Class.forName(className); 

      obj = clas.newInstance(); 

   } else { 

      clas = Class.forName(obj.getClass().getName()); 

   } 

   //得到obj類的一切特點 

   Field[] fileds = clas.getDeclaredFields();

   for (Field field : fileds) {

      String fieldName = field.getName();

      String fieldType = field.getType().getName();

      PropertyNameAnnotation annotation=field.getAnnotation(PropertyNameAnnotation.class);

      if (null == annotation) {

         return ;

      }

      String propertyCode = annotation.code();

        // 特點名的第一個字母大寫,與get或許is構成辦法名

        String firstCharUpper = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1, fieldName.length()); 

        Method method;

        //如果是boolean型則辦法名爲is*;反之爲get* 

        if (isBooleanType(fieldType)) { 

           method = clas.getMethod("is" + firstCharUpper, null); 

        } else { 

           method = clas.getMethod("get" + firstCharUpper, null); 

        } 

        if (isSysDefinedType(fieldType)) {

           //如果是體系類型則增加進入map

           String formatDateStr = isTimeType(fieldType, method, obj); 

           if (formatDateStr != null) { 

             dataMap.put(propertyCode, formatDateStr);

             continue; 

           }

           dataMap.put(propertyCode, method.invoke(obj, null) == null ? "" : method.invoke(obj, null));  //履行辦法,將成果保存到dataMap。

        }

    }

}


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