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?

Author: Robert Watkins

My name is Robert Watkins. I am a software developer and have been for over 20 years now. I currently work for people, but my opinions here are in no way endorsed by them (which is cool; their opinions aren’t endorsed by me either). My main professional interests are in Java development, using Agile methods, with a historical focus on building web based applications. I’m also a Mac-fan and love my iPhone, which I’m currently learning how to code for. I live and work in Brisbane, Australia, but I grew up in the Northern Territory, and still find Brisbane too cold (after 22 years here). I’m married, with two children and one cat. My politics are socialist in tendency, my religious affiliation is atheist (aka “none of the above”), my attitude is condescending and my moral standing is lying down.

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: