Annotation question answered

I’ve cleared up a question I didn’t get answered at the Developer Day; the syntax for using annotations.

The examples given in the session were all like this:

public @Fred void someMethod() {}

But I don’t like that syntax; if your annotations are long, it gets ugly. I prefer this one, which looks more like javadoc:

@Fred
public void someMethod() {}

Fortunately, you can do this; in fact, the examples in JSR175 are like this. It makes sense; the annotation is just another modifier, and Java lets you put modifiers in pretty much any order as long as they’re before the return type.

Placing the annotations in the line above is an important aspect to laying out the code. Consider what you do with multiple annotations, or annotations that take lots of parameters, like this one from the JSR175 spec:

// Normal annotation
@RequestForEnhancement(
id       = 2868724,
synopsis = "Provide time-travel functionality",
engineer = "Mr. Peabody",
date     = "4/1/2004"
)
public static void travelThroughTime(Date destination) { ... }

Can you imagine squeezing that into the gap between public and static?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s