创建注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface LeftWithSpace {
int len() default 0;
}
创建实体类
@Data
public class LeftWithSpaceDto {
@LeftWithSpace(len = 10)
private String a;
@LeftWithSpace(len = 20)
private String b;
}
实现
public class LeftWithSpaceService {
public static String leftMethod(Object obj, Class<?> claz) throws Exception {
Field[] fields = claz.getDeclaredFields();
StringBuilder sb = new StringBuilder();
for (Field field : fields) {
if (field.isAnnotationPresent(LeftWithSpace.class)) {
LeftWithSpace annotation = field.getAnnotation(LeftWithSpace.class);
int len = annotation.len();
field.setAccessible(true);
if (Objects.isNull(field.get(obj))) {
sb.append(leftWithSpaces("", len));
} else {
String str = field.get(obj).toString();
int length = StrUtil.bytes(str, "GBK").length;
if (length < len) {
sb.append(leftWithSpaces(str, len));
} else {
throw new RuntimeException("字段超长");
}
}
field.setAccessible(false);
}
field.setAccessible(true);
if (!Objects.isNull(field.get(obj))) {
sb.append(leftMethod(field.get(obj), field.get(obj).getClass()));
}
field.setAccessible(false);
}
return sb.toString();
}
private static String leftWithSpaces(String str, int len) {
if (StrUtil.isEmpty(str)) {
return StrUtil.fillAfter("", ' ', len);
}
int length = StrUtil.bytes(str, "GBK").length;
int strLen = str.length();
if (length == strLen) {
return StrUtil.fillAfter(str, ' ', len);
} else {
int i = length - strLen;
return StrUtil.fillAfter(str, ' ', len - i);
}
}
使用到的依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.8</version>
</dependency>