4

I have this code which str must be upper case and trimmed.

class A {
   private String str;

   public String getStr() { return str};

   public void setStr(String str) {
      if(str == null || str.equals(""))
           this.str = str;
      else 
           this.str = str.toUpperCase().trim();
   }

}

What I'm looking for is to make it annotation based. Which could be used either as @UpperCaseTrim private String str; or @UpperCaseTrim public void setStr(String str) {...};. How could this be implemented, maybe in a best way? What would the annotation processor be?

Dulguun Otgon
  • 1,925
  • 1
  • 19
  • 38
  • 3
    The option you have is likely to be the quickest and simplest. If you are developing your own library and have a few hours to kill you could create an annotation processor. – Peter Lawrey Jun 25 '15 at 19:27
  • 2
    Unless the annotation is necessary, id avoid it – user489041 Jun 25 '15 at 19:28
  • A duplicate of https://stackoverflow.com/questions/12195757/creating-custom-annotation-in-java-to-force-upper-or-lower-case ? – lrkwz Feb 02 '23 at 00:52

1 Answers1

1

To make things simple and reusable, use a static utility method:

public class MyUtils {
    public static String upperCaseTrim(String str) {
        return str == null ? null : str.toUpperCase().trim();
    }
}

then:

public void setStr(String str) {
    this.str = MyUtils.upperCaseTrim(str);
}

or with static import:

public void setStr(String str) {
    this.str = upperCaseTrim(str);
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722