I am trying to learn Servlet annotations and came across this snippet
@WebServlet(urlPatterns="/MyPattern", initParams={@WebInitParam(name="ccc", value="333")})
This makes sense to me. However, I don't understand why it is not like this
@WebServlet(urlPatterns="/MyPattern", initParams={(name="ccc", value="333"), (name="abc", value="1")})
So, the question is why we need to put @WebInitParam annotation when we already declared the attribute as initParams. It seems redundant to me, or am I missing something?
解决方案
As with most questions about language design choices we can only speculate here. I think some reasons for this are:
Keeping the language simple.
It is kind of redundant, but the syntax for annotations can be reused and does not require new language constructs. This makes it easier to parse and to read. Sure, It's longer, but it's also more explicit to write the annotation's name.
Don't restrict possible future language enhancements.
The proposed syntax would not work if annotations would support inheritance. I don't know if that's even a planned feature but it would not be possible to implement straightforward it if the type can be omitted.
In many cases an array of annotations seems like a workaround anyway. It can be avoided in Java 8, where you can add multiple annotations of the same type:
@WebServlet(urlPatterns="/MyPattern")
@WebInitParam(name="ccc", value="333")
@WebInitParam(name="abc", value="1")
(I don't know if the servlet api actually supports this yet though)