Java - 注解使用示例(解析注解格式化类生成字符串)

目的

使用注解标注对象属性,用于格式化输出字符串

注解

我们主要创建以下两个注解:

  1. @Label:用于定制输出字段的名称
  2. @Format :用于格式化时间类型的字段

@Label

package test2;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by Joe on 2018/2/23.
 * 用于定制输出字段的名称
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Label {
    String value() default "";
}

@Format

package test2;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by Joe on 2018/2/23.
 * 用于定义日期类型的输出格式
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Format {
    String pattern() default "yyyy-MM-dd HH:mm:ss";

    String timezone() default "GMT+8";
}

定义Student类,使用注解对字段进行标注

package test2;

import java.util.Date;

/**
 * Created by Joe on 2018/2/23.
 */
public class Student {
    @Label("姓名")
    String name;

    @Label("出生日期")
    @Format(pattern = "yyyy/MM/dd")
    Date born;

    @Label("分数")
    double score;

    public Student(String name, Date born, double score) {
        this.name = name;
        this.born = born;
        this.score = score;
    }
}

编写格式化处理

package test2;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * Created by Joe on 2018/2/23.
 */
public class SimpleFormatter {
    public static String format(Object obj) {
        try {
            Class cls = obj.getClass();
            StringBuilder stringBuilder = new StringBuilder();

            for (Field field : cls.getDeclaredFields()) {
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }

                Label label = field.getAnnotation(Label.class);
                String name = label != null ? label.value() : field.getName();

                Object value = field.get(obj);
                if (value != null && field.getType() == Date.class) {
                    value = formatDate(field, value);
                }

                stringBuilder.append(name + ":" + value + "\n");
            }

            return stringBuilder.toString();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return "";
    }

    private static Object formatDate(Field field, Object value) {
        Format format = field.getAnnotation(Format.class);
        if (format != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat(format.pattern());
            dateFormat.setTimeZone(TimeZone.getTimeZone(format.timezone()));

            return dateFormat.format(value);
        }

        return value;
    }
}

测试

package test2;

import java.text.SimpleDateFormat;

/**
 * Created by Joe on 2018/2/23.
 */
public class Main {
    public static void main(String[] args) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Student student = new Student("张三", simpleDateFormat.parse("1990-12-12"), 80.9);

        System.out.println(SimpleFormatter.format(student));
    }
}

输出结果:

姓名:张三
出生日期:1990/12/12
分数:80.9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值