projectlombok / lombok

Very spicy additions to the Java programming language.
https://projectlombok.org/
Other
12.93k stars 2.4k forks source link

[FEATURE] Truncate the large String variable in toString() #3762

Open arjundt opened 1 month ago

arjundt commented 1 month ago

This feature will help to truncate the long string variables(eg, photos, private/public keys, json strings etc) in toString() method. Although there is is an annotation to exclude a variable in toString() but incase someone wanted that variable in truncated format then this feature will be very helpful. Please find the example of truncated and non-truncated toString() method below.

Non-truncated toString: Response(txnNo=1, photo=iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAwFBMVEX/////mTMSiAfl5ebk5OXm5uf4+Pjt7e719fX7+/vx8fHr6+z/5NTU4dT/kxsAgAD/lScAfgDq7eoAAH4AAHoAAIT7/vrE18P/kBbP4s7/48/x1sTtz7vt7fa0tNNHR5gqKpF6erKZmcZycrCSksKFhbfc3OxZWaXGxt/Q0OXm5vPv7/YNDYhMTJxDQ5qNjcIAAHKZmcBCQqA4OJwUFIitrcq+vtliYqmAgLT/iwD+9vKkpMq3t9tvb68AAI4AdgCW6bhPAAAIrUlEQVR4nO1ci3ajNhBVK/ESbbdrIOluCjY2Jn4ljZNskl3v4///qhKQ8BIvB2EjmHMcOdc6FuNhZq4uxgAAIEMJymREElTIoEAJJVBYhuIYVZlzKSqVobgM1d5QST8SpX+G4CGCKPAQRkcCUV0Up1GYm6tWodE7aBEqQai3g6IIBbIsq4qiqGQkAyYDJqNAKPkoUfABo0yIGqO4aq4aonqMam/hRKmPvQyVmqCIovkkqUxJXJWolSlZmnwJ9OjkS6LdxhCeIIZnky/c8lD8Wlo3+XreD1EYFxSlDkLvQ3GIajGqx3MpqlahOI3CBqiUQdtzq9LZLt1CZ90ttNa7RePyUll0KstLHm2pvLDQcyzwraIgFYz2m7+am5tp6O03f4QG2S2EimEGFSQPcTEqWC3NhhOeZT9se/ckBqcpZTr83JLruKW824EqXlr31HxHt+iIwKE63UKk/eErOoA9viBaGypGxe8WQmttsDdaWwkpq0RFqKUsqja83RM/TtNUa2u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cCZzUEM0TuBAFxacmakbgKqlaBpWKCFwrVC3bLUqpWnMCV4uqpcle21Qt4WGPqVo9Apdpx+1QNfbcVKU5mqo1J3Did4uCGL6LqrHnnorAnSPRahUFqY/9PVSNPbeUwDED1zaBA3WTr+e7Jz5UTa5D1ZTjqVpjre2VEKWpGoMmKQ3QI+hX2wQup0QNW2vLHt+otXVG1UrQjipNYm57laZ0UxhXGjCMbjFqbX1GC5n3qLX1Z/c0UK2NQeDOnqol0LzWVkRkhq21lRG4IWptXVO1BMqFqlV+AYP7pjCB/g9XKIdSjV+bXgAAAABJRU5ErkJggg==)

Truncated toString: Response(txnNo=1, photo=iVBORw0KGgoAAAAN...)
victorwss commented 1 month ago

I think that this is a very special corner case, exactly where you should write a custom old-fashioned toString() instead of having it being generated by Lombok.

Of course, I might be wrong, but I don't think that this is common enough to be worth implementing.

Anyway, if this would be implemented, I think that this would be relatively easy to add something like @Truncate(maxLength = 16).

bmrammel commented 2 weeks ago

There was another issue made about modifying the output of specific fields in a toString method and the solution was to do something like this

@Data
public class Picture {

    @ToString.Exclude
    private String photo;

    @ToString.Include(name = "photo")
    public String getTruncatedPhoto() {
        return truncate(photo);
    }

}