Search code examples
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 done by

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

    Now Implement your the customDeSerializer as below

    public class CustomDeSerializer extends JsonDeserializer<String> {
    @Override
    public String deserialize(JsonParser p, DeserializationContext ctx)
            throws IOException {
        String str = p.getText();
        try {
            return str.trim();
        } catch (Exception e) {
            System.err.println(e);
            return null;
        }
    }
    

    }