Tuesday April 04, 2006
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: varargs, annotation, JavaEE
Posted at 05:22PM Apr 04, 2006 by chengfang in Glassfish | Comments[0]