0

I'm trying to make a custom annotation at class level, to genrate a ToString() method which returns all the field value in a string as they are, but if any field is of type List then we want only first 10 elements from List not whole list (as in lombok it prints whole list).

    @Getter
    @Setter
    public class Entity{

    private EntityType type; //type is a string (modifier, getter, setter) 
    private String entityName;
    private String entityValue;
    private List<EntityList> entityList; //list retrieve from database can contain 100s of element

    @Override
    //primarly using for logging purposes
    public String toString() {
        return "SomeEntity [type=" + type + ", entityName=" + entityName + ", attributeValue="
                + entityValue + ", entityList" = entityList + "]";
    }
    }

Here toString method is returning all elements of Arraylist, which results a messy logs (if list contains say 1000 elements). To avoid this, I want to use a custom ToString annotation, which generates an toString equivalent at complie time and returns all fields, but if any List type is present then only first 10 elements from list would be returned/printed.

I've tried this

    @Override
    //primarly using for logging purposes
    public String toString() {
        return "SomeEntity [type=" + type + ", entityName=" + entityName + ", attributeValue="
                + entityValue + ", entityList" = Utils.toString(entityList) + "]";
    }
    public class Utils {

    private static final int TO_STRING_COLLECTION_LIMIT = 10;

    public static <E> String toString(Collection<E> collection) {
        if (CollectionUtils.isEmpty(collection)) {
            return "<empty>";
        } else {
            return "{size=" + collection.size() + ", collection=" +
                    collection.stream().limit(TO_STRING_COLLECTION_LIMIT)
                            .map(Object::toString).collect(Collectors.joining(",", "[", "]")) +
                    "}";
        }
    }
    }

but for having an extendable solution I want to create a custom annotation.

How I can create this custom ToString annotation in Spring Boot?

I have checked various online forums but haven't got any relevant information to implement same.

Kindly help.

Thanks

0 Answers0