0

Appreciate any help for creating custom annotation in JAVA by forcing Upper or Lower case for a pojo field. Like to get something like below

// CaseMode enum would be
public enum CaseMode {
   UPPER, LOWER;
}

@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Case {
    // NEED HELP HERE
}

public class Customer {
    @Case(value=CaseMode.UPPER)
    private String fName; 
    { set; get; }
}

setter method in Customer Object by default should force data to be stored in UPPERCASE or LOWERCASE based on annotation. Appreciate any help to get this.

Thanks in advance

Anand
  • 1,845
  • 2
  • 20
  • 25

2 Answers2

1

Annotations are passive elements in Java; they can not have any behavior. As @maba said, you can not write any code inside an annotation declaration.

In order to have something similar to what you are trying to do, you need something which detects the annotation and performs some work. You have a few choices.

Writing a custom compile-time annotation processor allows you to preprocess the source code before compilation.

Aspect oriented programming can work both at compile and at run time. It's relatively easy to understand, needs however some tooling to be set up together with your project, depending where you deploy it.

Dynamic proxies are simple as well, but you need to change the way your code accesses the objects, probably by declaring some interfaces and using those instead of the classes, etc.

Code generation libraries fall on the complex side of the spectrum, giving lots of flexibility (they are for instance how Hibernate does its magic with your POJO objects).

Community
  • 1
  • 1
Flavio
  • 11,925
  • 3
  • 32
  • 36
  • Thanks Flavio. Let me check with your suggestions. Happened to find link where custom validator was developed http://musingsofaprogrammingaddict.blogspot.in/2009/02/getting-started-with-jsr-303-bean.html. I was hoping to develop a custom converter – Anand Aug 30 '12 at 12:39
0

Your statement // NEED HELP HERE should be according to the following:

@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Case {
    CaseMode value();
}

If you think that you can have some code in there then you are wrong.

maba
  • 47,113
  • 10
  • 108
  • 118
  • Thanks, got that. Can you please suggest on how to get Custom converter for POJO member data conversion. Thanks in advance – Anand Aug 30 '12 at 12:26