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。

        }

    }

}


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