1. 程式人生 > >註解使用示例(解析註解格式化類生成字串)

註解使用示例(解析註解格式化類生成字串)

目的

使用註解標註物件屬性,用於格式化輸出字串

註解

我們主要建立以下兩個註解:

  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