简体   繁体   中英

Is there a limit on the number of Java annotations on a field?

Is there a limit on the number of Java annotations on a field? I couldn't find any information on that point.

No, there is nothing about a limit in the spec.

See here: http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf

The only limit you encounter for java files in general are os-wide limits like max. file size on some filesystems or - in hardcore cases - the disk size. Some systems might have problems compiling or running a 100gb .java/.class file...

Do as you please. It's just that it's probably bad design. Keeping it bellow 10 is a good rule of thumb, I'd say.

Edit: It seems there is, after all, a limit. At least on runtime annotations on methods.

Note that a maximum of 65535 runtime-visible Java programming language annotations may be directly attached to a program element.

Not sure if this counts for fields too.

So, I guess the answer depends on the kind of annotations you want to add.

Nothing about that in the language spec though. I guess they didn't really think someone would try it.

Well here is a limit from the class file format specification .

4.7.18. The RuntimeVisibleParameterAnnotations attribute

The RuntimeVisibleParameterAnnotations attribute is a variable-length attribute in the attributes table of the method_info (§4.6) structure. The RuntimeVisibleParameterAnnotations attribute records runtime-visible Java programming language annotations on the parameters of the corresponding method.

Note that a maximum of 65535 runtime-visible Java programming language annotations may be directly attached to a program element.

Edit

The link above also mentions RuntimeVisibleAnnotations and RuntimeInvisibleAnnotations for classes, methods and elements - the limit on each is again 65535. The 65535 is also the max value that the structure can contain (unsigned 16 bit integer), you will likely run into other limitations long before you hit that number.

I suspect the limit is higher than the numebr of annotations you have (you can only add them once) or would be likely to want to add.

If you every wanted to add more data, you can value arrays of annotations as values of an annotation, but including rich information in Strings is a common way to add more information eg in JSon format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM