package com.xxx.common.util; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.lang.reflect.Field; /** * @version 1.0.0 * @date 2021-01-15 17:53 */ @Slf4j public class TrimUtil { public static void trimStringFieldInObject(Class<?> clazz, Object t) { Field[] fields = clazz.getClass().getFields(); for (Field field : fields) { try { if (field.get(t) instanceof String) { Object o = field.get(t); String s = (String) o; field.set(t, StringUtils.trimToEmpty(s)); } } catch (IllegalAccessException e) { log.warn("converting field {} error", field.getName()); } } } }
https://stackoverflow.com/questions/9189520/trim-all-strings-elements-in-a-complex-object