java注解实战

来源:互联网 发布:要不要复读知乎 编辑:程序博客网 时间:2024/06/01 07:22

java注解的入门

入门基础知识
自行百度了解,或者根据下图了解。
这里写图片描述

自定义注解的高阶实战

应用场景举例:外部系统传入的请求对象的属性值不规范(例如值的长度不足或者太长等)或者说是外部系统认可的值但是不符合我们规范(例如两个系统间的字段映射关系不一致),那么在本系统中需要做一个(抽象出来)统一的前置的数据转换,就需要用到自定义注解和解析。
1.下面是自定义注解类ApiElement

package test;import java.lang.annotation.*;/** * <p>渠道api element 注解</p> * <pre> *     author      JasonGao *     date        2017/7/24 *     email       xxxx * </pre> */@Retention(RetentionPolicy.RUNTIME)@Documented@Inheritedpublic @interface ApiElement {    /**     * 字段长度     *     * @return     */    int length() default 0;    /**     * 是否填充     *     * @return     */    boolean fill() default false;    /**     * 左侧填充,默认 false(即右边填充)     *     * @return     */    boolean leftFill() default false;    /**     * 填充值     *     * @return     */    String fillValue() default " ";}

2.含有注解标签的java对象。

package test;/** * <p>基础信息Model</p> */public class BasicInfoModel {    /**     * 结算单号     */    private String settleOrderNo;    /**     * 划款指令号     */    private String transferNo;    /**     * 付款币种     */    private String paycurrtype;    /**     * 收款币种     */    private String revcurrtype;    /**     * 机构标示 商户组织机构号     */    private String institutionId;    /**     * 交易时间     */    private String transactionDate;    /**     * 交易笔数     */    @ApiElement(length = 12, fill = true, leftFill = true, fillValue = "0")    private String count;    /**     * 交易金额     */    private String amount;    /**     * 文件批次号     */    private String fileBatchNo;    /**     * 文件名     */    private String filename;    /**     * 组织机构名称     */    private String orgName;    /**     * 住所/营业场所代码     */    private String placeBizCode;    /**     * 机构地址     */    private String orgAddress;    /**     * 邮政编码     */    private String zipCode;    /**     * 所属行业代码     */    private String industryCode;    /**     * 经济类型代码     */    private String economicType;    /**     * 常驻国家代码     */    private String countryCode;    /**     * 是否特殊经济区内企业     */    private String isEconomic;    /**     * 企业类型     */    private String enterpriseType;    /**     * 投资者国别代码1     */    private String investment1;    /**     * 投资者国别代码2     */    private String investment2;    /**     * 投资者国别代码3     */    private String investment3;    /**     * 投资者国别代码4     */    private String investment4;    /**     * 投资者国别代码5     */    private String investment5;    /**     * 邮箱     */    private String email;    /**     * 申报方式     */    private String declareMode;    /**     * 备注     */    private String remark;    /**     * 机构联系人     */    private String orgContactName;    /**     * 机构联系电话     */    private String orgTel;    /**     * 机构传真电话     */    private String orgFax;    //TODO:get、set、toString方法略。。。}

3.下面是对注解类的实战使用(将含有注解标签的java对象,转换成注解标签所标识的格式)的工具类。

package test;import java.lang.reflect.Field;/** * <p>转换对象到BasicInfoModel 通过ApiElement注解处理</p> * <pre> * <pre> *     author      JasonGao *     date        2017/7/24 *     email       xxxx * </pre> */public class ApiElementConvertSupport {    /**     * 转换方法     * <p>数据长度使用字节长度</p>     *     * @param object     * @param charset 字符集,例如utf-8     * @return     */    public static BasicInfoModel convertByByteSize(Object object, String charset) throws Exception {        Field[] fields = object.getClass().getDeclaredFields(); //获得某个类的所有声明的字段,即包括public、private和proteced,但是不包括父类的申明字段。        for (Field field : fields) {            field.setAccessible(true);  //类中的成员变量为private,故必须进行此操作,以取消Java的权限控制检查            Object tmpVal = field.get(object);            if (tmpVal != null) {                // 获取值                String value = tmpVal.toString();                // 获取ApiElement注解                ApiElement apiElement = field.getAnnotation(ApiElement.class);                if (apiElement != null) {                    int length      = apiElement.length();                    int valueLength = value.getBytes(charset).length;                    if (valueLength < length && apiElement.fill()) {                        // 小于指定长度 且需要填充                        String fillValue = apiElement.fillValue();                        if (apiElement.leftFill()) {                            // 左填充处理                            for (int i = 0; i < length - valueLength; i++) {                                value = fillValue + value;                            }                        } else {                            // 右填充处理                            for (int i = 0; i < length - valueLength; i++) {                                value = value + fillValue;                            }                        }                    }                    field.set(object, value);                }            }        }        BasicInfoModel model = new BasicInfoModel();        return model;    }}

4.下面是调用注解解析的工具类的demo。

 public static void main(String[] args) throws Exception {     BasicInfoModel basicInfoModel = new BasicInfoModel();     //TODO:给basicInfoModel对象的各个属性set值。。。。     BasicInfoModel result = processorParams(basicInfoModel, "xxxxxx");     System.out.println(result); }/**     * 根据业务属性处理参数     *     * @param basicInfoModel     */    private static BasicInfoModel processorParams(BasicInfoModel basicInfoModel, String charset) throws Exception {        basicInfoModel = ApiElementConvertSupport.convertByByteSize(basicInfoModel, charset);        System.out.println("[BasicInfoModel]请求消息前置处理Handler | 参数处理完成. basicInfoModel = [" + basicInfoModel.toString() + "]");        return basicInfoModel;    }
原创粉丝点击