javaannotationstrim

Java custom annotation for a behaviour like trim


I have to write the trim functionality like below.

public void setUserComment (String value) {
    this.userComment  = (value != null) ? value.trim() : value;
}

But this needs to apply this in lots of places in our existing place. any idea that uses custom annotation for this behavior. like.

@MyCustomTrim
public void setUserComment (String value) {
    this.userComment  = value;
}

Solution

  • Yes, we can easily do it with

    @JsonDeserialize(using = TrimDeserializer.class)
    private String name;
    

    Now implement your TrimDeserializer as below

    public class TrimDeserializer extends JsonDeserializer<String> {
        @Override
        public String deserialize(JsonParser parser, DeserializationContext ctx) throws IOException {
            String str = parser.getText();
    
            if (str == null) {
                return null;
            }
    
            return str.trim();
        }
    }