vendredi 15 juillet 2022

Better way to trim strength lengths in object than reflection

I have a custom annotation defined for trimming strings based on the size specified.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Trim {
    public int size();
}

and an entity where I am using it

@Entity
@Table
@Data
public class Users {

    @Id
    private Long id;

    @Trim(size = 10)
    private String firstName;

    @Trim(size = 10)
    private String middleName;

    @Trim(size = 10)
    private String lastName;

    @Trim(size = 25)
    private String address;

}

The goal is to trim size based on what's specified in the annotation. For ex: the address column has a size constraint of 25 characters on the database table and if the address field contains more than 25 characters we need to trim the string to only consider the first 25 characters prior to calling save() on the entity. This can't be done in code because there are many fields with size constraints in many tables.

This is currently done through reflections and the function below works but I am wondering if there is a better way than this.

    public User trimStrings(User u) throws IllegalAccessException {
        for (Field f : u.getClass().getDeclaredFields()) {
            f.setAccessible(true);
            if (f.get(u) != null && f.isAnnotationPresent(Trim.class)) {
                Trim t = f.getDeclaredAnnotation(Trim.class);
                String str = (String) f.get(u);
                int siz = Math.min(t.size(), str.length());
                f.set(u, str.substring(0, siz));
            }
            f.setAccessible(false);
        }
        return u;
    }




Aucun commentaire:

Enregistrer un commentaire