No more ({ }) for single-element annotation value, thanks to varargs

I found this accidentally that I can assign a single value to an array when specifying annotation fields.  The other day when I wrote a simple EJB3 testcase, I realized there was a type mismatch: the value of @Interceptors is declared as Class[], but I just gave it a single value (MyInterceptors.class).  But surprisingly no complaints from javac!

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;

@Stateless
@Interceptors(MyInterceptors.class)
public class HelloBean {...} 

I'm so used to the strong-typing that I couldn't believe this.  I thought I was using a wrong version of javax.interceptor.Interceptors.class in an old javaee.jar.  I even searched all my classpath for any duplicate jar/class files.

Now with the help of Variable Arguments (varargs), I can simplify

@Interceptors({MyInterceptors.class}) ==> @Interceptors(MyInterceptors.class)

@Remote({HelloIF.class}) ==> @Remote(HelloIF.class)

@Local({HelloIF.class}) ==> @Local(HelloIF.class)

@EntityListeners({MyListener.class}) ==> @EntityListeners(MyListener.class)

From a documentation point of view, the simpler form hides the true field type and may cause confusion. 

Of course, for multi-element value you still use the old style:

@Interceptors({MyInterceptors.class, HisInterceptor.class})

technorati tags: , ,

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

Cheng Fang

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today