0

I have a small use case. Consider a class-

@Myannotation
class Abc {
   String pqr;
   String lmn;
   static List<String> xyz;
}

xyz will have ["pqr", "lmn",..]. I want to create custom annotation for class Abc to initialize list xyz with other variables' names like "pqr". So there are 2 sub problems here -

  • a. Creating Custom annotation for class.- (I got a little idea about it from the online articles on how to create. But a little unsure on how to do the processing of the annotation.)

Should start something like

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.Type)
public @interface Myannotation {
}
  • b. How to get variable names of the class? - (Is that even possible for same class?)

Can I do that? If yes, How can I do that?

Leena
  • 703
  • 1
  • 12
  • 21
  • 1
    Annotation processors cannot alter existing classes, so you could not alter Abc in any way. You could use the annotation to generate some `AbcFactory` class, for example, which creates instances with the right parameters – Michael Sep 24 '20 at 11:04
  • @Michael So can I create another class which will hold this list and will get populated automatically using annotation? – Leena Sep 24 '20 at 11:11
  • Yes, but it is beyond the scope of StackOverflow to solve that for you. You can look into tutorials on how to write an annotation processor. Then you'll have to iterate the fields of the class, and generate some source code. I use [JavaPoet](https://github.com/square/javapoet) – Michael Sep 24 '20 at 11:18
  • Thanks @Michael i got a pretty good idea to simplify my problem. – Leena Sep 24 '20 at 11:23

0 Answers0