2

Is there some way to use a single annotation for multiple variables in Java? I have a class with a fairly large number of variables that all require the same annotation, and while I could copy paste the same annotation over and over, I am worried that this will affect the readability of my code.

I've tried searching everywhere but haven't found anything, leading me to believe that this likely isn't possible, but optimally it would be something like this; Instead of:

@Annotation
int var1;
@Annotation
int var2;
...

Something like:

@Annotation:
   int var1;
   int var2;
...

or maybe

@Annotation {
    int var1;
    int var2;
}
vchad
  • 41
  • 6

2 Answers2

1

That depends on whether the library you're using that uses these annotations support a class level annotation.

For example, using jackson library, you can supply a list of variables at class level:

@JsonIgnoreProperties({ "bookName", "bookCategory" })
public class Book {

instead of writing @JsonIgnore over individual fields.

Kartik
  • 7,677
  • 4
  • 28
  • 50
  • The annotation in question does not have such a feature. Is there any way for me to create a new annotation that would use the old one to do a similar task? – vchad Jul 11 '19 at 05:54
  • Potentially. You'll have to override the library class (assuming it's not final and is accessible) to make it understand your custom annotation. But I think it's better to keep things simple and just use the given annotation repeatedly. – Kartik Jul 11 '19 at 05:59
0

You can group variables of the same type and declare them on one line with the annotation applying to all of them.

@Annotation
int var1, var2, var3;
FThompson
  • 28,352
  • 13
  • 60
  • 93
  • 1
    Sorry, I see now that it wasn't very clear from the question, but in my case I actually have variables of many different types. int, String, MyClass[], etc... for example. – vchad Jul 11 '19 at 06:16