目的
使用注解标注对象属性,用于格式化输出字符串
注解
我们主要创建以下两个注解:
- @Label:用于定制输出字段的名称
- @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