在我们实际工作中,可能会遇到要将用户访问接口的一些参数保存或导出,但是直接使用tostring方法只会输出“属性:属性值”样式的字符串。通过以下方法可以轻松实现将java对象的属性以字符串“字段中文:值”输出。
具体为:自定义一个注解,并写一个打印方法,对象调用这个方法后,便可以输出。
1.自定义一个注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ChineseName {
String value();
}
2.将对象的属性添加上注解

3.写一个打印属性的方法
public static String printProperties(Object obj) {
Class<?> clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
StringBuilder properties = new StringBuilder();
for (int i = 0; i < fields.length; i++){
Field field = fields[i];
field.setAccessible(true); // 确保可以访问私有字段
ChineseName chineseName = field.getAnnotation(ChineseName.class);
if (chineseName != null) {
try {
Object value = field.get(obj);
if (i > 0) {
properties.append(","); // 除了第一个属性外,其他属性前都添加逗号
}
properties.append(chineseName.value() + ":" + value);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}else {
log.info("无法打印属性" + field + "请为其添加@ChineseName注解");
}
}
return properties.toString();
}
这样对象.printProperties方法打印出中文格式的内容
![]()
4901

被折叠的 条评论
为什么被折叠?



