File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Annotations in Java5 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Annotations in Java5" Watch "Annotations in Java5" New topic
Author

Annotations in Java5

Jaikiran Pai
Marshal

Joined: Jul 20, 2005
Posts: 10289
    
168

I was going through the new feature of Java5, "Annotations". Though i have seen examples of using annotations in EJB3, i dont have a clear idea about annotation. Here's a extract from the Java5 docs, which explains Annotations :

Here is an example annotation type declaration:

public @interface RequestForEnhancement {
int id();
String synopsis();
String engineer() default "[unassigned]";
String date(); default "[unimplemented]";
}


- What exactly does this mean, in simple terms. My interpretation is, we are defining an annotation type which contains 4 methods. Is my understanding correct? And is this all the above type declaration conveys, or is there something more?

The next extract:

Once an annotation type is defined, you can use it to annotate declarations. Annotations consist of an at-sign (@) followed by an annotation type and a parenthesized list of element-value pairs. The values must be compile-time constants. Here is a method declaration with an annotation corresponding to the annotation type declared above:

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


Now, how do i interpret this piece? I could not understand much out of this, except for the fact that we have a method travelThroughTime signature preceeded by the annotation. What purpose does the annotation serve to this method? And what significance do the values in the annotation declaration hold? I also see that the elements in the element-value pair have the same name as the method names in the annotation type(Ex: the id() method in the annotation type and the id=2868724 element in the annotation declaration). Is this just a co-incidence or does this serve a purpose?

Any help in trying to understand annotations, will be appreciated.
Thank you.
[ July 18, 2006: Message edited by: jaikiran pai ]

[My Blog] [JavaRanch Journal]
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14432
    
  23

Annotations are used to specify metadata to classes, methods etc.

That means that you use annotations to specify certain properties of the classes, methods etc. that you use the annotations on.

In the past, there have been several ad-hoc mechanisms in Java for this purpose. Examples are marker interfaces (Serializable for example) and the keyword transient. With annotations, there's now a more generic way to add metadata to your classes, methods etc.

More info:
The Java Tutorial - Annotations
An Introduction to Java Annotations


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Jeroen T Wenting
Ranch Hand

Joined: Apr 21, 2006
Posts: 1847
I've seen very few systems where they were useful, and none at all where some other existing language feature couldn't have done the same thing.

Only place I've ever used them myself is to mark a set of classes which are controlled through a servlet with the request parameters each individual class supports so I can build the form for each of them on the fly.
Would have been possible using several other systems as well, but I thought it would be a nice experiment for an otherwise pretty useless part of the language.


42
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Jeroen T Wenting:
I've seen very few systems where they were useful, and none at all where some other existing language feature couldn't have done the same thing.

Only place I've ever used them myself is to mark a set of classes which are controlled through a servlet with the request parameters each individual class supports so I can build the form for each of them on the fly.
Would have been possible using several other systems as well, but I thought it would be a nice experiment for an otherwise pretty useless part of the language.


While annotations are generally poorly designed and quite useless in a majority of cases (due to many limitations to maintain so-called backward compatibility), they are at least more decent than other artifacts of "JSR expert groups", which generally produce something worse than the worst thing that the imagination (of myself at least) is capable of dreaming of - at least there is something to learn there.

Apparent cyncism/realism aside, there are some use cases that are at least better than the alternative. Consider the 'throws' keyword - while signal handling in Java is utterly flawed and best implemented as a "quasi-continuation" avoiding exceptions altogether due to the implicit call stack unrolling and no criteria to decide the appropriate execution path - there are a lot of misled programmers (who know only the basics of imperative programming I assume) who believe that unchecked exceptions are the only legitimate exceptions. Given this (flawed, but anyway...) argument, the "throws" keyword becomes a redundant language binding better implemented as an annotation. Another case is the metadata applied to JUnit "test cases" (I hate that term - it is loaded, incorrect and as a result, misleading) where the method name must start with "test" in order for it to qualify for execution. Isn't this a prime candidate for more appropriate metadata such as annotations? I'm sure there are many more examples.


Tony Morris
Java Q&A (FAQ, Trivia)
Jeroen T Wenting
Ranch Hand

Joined: Apr 21, 2006
Posts: 1847
You seem to hate Java with a vengeance. Maybe it's time you moved on to greener pastures, like Bruce Tate did (who always was a great Java advocate, until he got a job working for a Ruby shop when suddenly Java was the worst thing that had ever happened).

I agree that many JSR groups produce garbage. That's the entire problem with the JCP as it stands, there's no entry exam to see if people entering have the best interest of the platform in mind and know what they're talking about.
And with the multitude of kids (and older people) screaming their demands for "improvements" in forums and newsgroups, the future sometimes does look bleak.

Annotations are however the worst that's made it into a released version of the platform so far (though Mustang will see more madness, with the inclusion of a complete database engine, SOAP server, and webserver as part of the core API).
Jaikiran Pai
Marshal

Joined: Jul 20, 2005
Posts: 10289
    
168

I've seen very few systems where they were useful, and none at all where some other existing language feature couldn't have done the same thing


Thats right. After having a brief look at Annotations, i do prefer sticking with the traditional approach in Java.
Jaikiran Pai
Marshal

Joined: Jul 20, 2005
Posts: 10289
    
168

Annotations are however the worst that's made it into a released version of the platform so far


I have heard many others say the same.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Jeroen T Wenting:
You seem to hate Java with a vengeance.

I neither hate nor love it - I have no emotional attachment to it whatsoever - I simply accept it for what it is and refuse to lie to myself or allow others (i.e. books, corporations) to lie to me about what it isn't - the single biggest reason that I no longer work for The Filth. I empathise with those who have internalised the artifacts of what I perceive to be a propaganda machine and feel very mildly compelled to correct it - where requested, which is why it might appear sometimes that I "hate Java". More importantly, I am definitely driven to offer an alternative to the erroneous establishment for those who request it and have no choice but to place trust in someone else, but are potentially misled by hidden primary agendas. I suspect that you might behave in a similar way. I do this with the proclamation that I have no other agenda but to purport truth as I perceive it, as opposed to say, the latest "this is how Java works" book, which is primarily "make money", followed by "purport some form of perceived truth" i.e. the latter gives way to the former.

While this might seem ideological and all, I concede that there is an awful paradox underlying it all. Historically, society has labelled people such as myself as heretics
Rajah Nagur
Ranch Hand

Joined: Nov 06, 2002
Posts: 239
Annotations definitely help
* to reduce the boiler plate code (JAX-RPC, Webservices, EJBs etc)
* in generating deployment descriptors
* in generating "side files" like BeanInfo classes for Java Beans
* aid in Testing frameworks like JUnit/TestNG

There is huge potential to create custom annotations which can help in documentation, role based security, etc etc.

I don't understand why many are against Annotations. Earlier when this feature was not available, many cribbed about this, now when it is available it looks complex. Strange. If it seems not usable, ingore it.


You can't wake a person who is <b><i>pretending</i></b> to be asleep.<br />Like what <b>"it"</b> does not like - <i> Gurdjieff </i>
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14432
    
  23

Originally posted by Jeroen T Wenting:
I've seen very few systems where they were useful, and none at all where some other existing language feature couldn't have done the same thing.

There are a number of applications where annotations are very useful: JUnit 4, for example. With JUnit 4, you don't have to subclass junit.framework.TestCase anymore and your test methods don't have to adhere to a specific naming convention - instead, you just add a @Test annotation to indicate that it's a JUnit test method. The big advantage is that you're not tying your code to the JUnit library very tightly.

In EJB 3.0 annotations are used to make writing EJB's much easier, and also in Java EE 5 annotations are used to make writing web services much easier. The only thing you have to do to make a web service is add a @WebService annotation to your method and you're done!

Ofcourse you could probably have done those things with existing language features, but it would have been more cumbersome and less clear.

Originally posted by Jeroen T Wenting:
Annotations are however the worst that's made it into a released version of the platform so far (though Mustang will see more madness, with the inclusion of a complete database engine, SOAP server, and webserver as part of the core API).

Please explain why you think they are so bad, because I'm not convinced yet.

Going offtopic: There will not be a database engine in the Mustang JRE. They're just including a database in the JDK. No big deal. Normal people who download the JRE to run Java programs won't notice anything. And there is NOT going to be a SOAP server and webserver in Java SE. Only stuff to make writing SOAP clients easier.

Originally posted by jaikiran pai:
Thats right. After having a brief look at Annotations, i do prefer sticking with the traditional approach in Java.

So simply because you don't understand a new and very useful feature, and because others tell you it's not useful without any clear motivation, you decide to not use it? Note that the rest of the world is going to use annotations, whether you like it or not, and if you don't know annotations, your'e going to stay behind.
[ July 19, 2006: Message edited by: Jesper Young ]
Jaikiran Pai
Marshal

Joined: Jul 20, 2005
Posts: 10289
    
168

Note that the rest of the world is going to use annotations, whether you like it or not, and if you don't know annotations, your'e going to stay behind.


You are right. I never meant that i would not learn annotations, rather i meant that learning annotation will not be a high priority thing for me.

And going back to my first couple of questions in this topic, i never really got an answer to those. I decided, instead of going through the docs again and again, it would be better to try and write my own annotation types to get to know them better
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14432
    
  23

OK, let's have another look at your original questions.

What exactly does this mean, in simple terms. My interpretation is, we are defining an annotation type which contains 4 methods. Is my understanding correct? And is this all the above type declaration conveys, or is there something more?

The things you define in the annotation type declaration are not really methods, they're really the parameters of the declaration type. I don't know why the inventors of Java annotations chose this particular notation, it's a bit strange. And this is all, there is nothing more that you have to write (there is no implementation of those "methods").

Now, how do i interpret this piece? I could not understand much out of this, except for the fact that we have a method travelThroughTime signature preceeded by the annotation. What purpose does the annotation serve to this method? And what significance do the values in the annotation declaration hold? I also see that the elements in the element-value pair have the same name as the method names in the annotation type(Ex: the id() method in the annotation type and the id=2868724 element in the annotation declaration). Is this just a co-incidence or does this serve a purpose?


The interpretation is this: The method travelThroughTime(...) is annotated with a RequestForEnhancement annotation. So there is a request for enhancement associated with this method. The annotation has parameters named id, synopsis, engineer and date, with the specified values. Ofcourse it's not a coincidence that the parameter names are the same as the "methods" that you see in the annotation declaration.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

You'll note that the @Test annotation from JUnit 4 is taken directly from JTiger/TestNG which both use annotations for contract metadata.


I think it's more directly taken from NUnit, which is older than TestNG, and better known in the TDD community than JTiger.
[ July 19, 2006: Message edited by: Ilja Preuss ]
Jaikiran Pai
Marshal

Joined: Jul 20, 2005
Posts: 10289
    
168

The things you define in the annotation type declaration are not really methods, they're really the parameters of the declaration type


That answers my first question. Thank you.

The interpretation is this: The method travelThroughTime(...) is annotated with a RequestForEnhancement annotation. So there is a request for enhancement associated with this method


Now that i know that there is a request for enhancement associated with this method, how actually will i make use of this information? Let me put it this way, where and how will the information which i passed on:
id = 2868724,
synopsis = "Enable time-travel",
engineer = "Mr. Peabody",
date = "4/1/3007"

through the annotation declaration, be used?

Ofcourse it's not a coincidence that the parameter names are the same as the "methods" that you see in the annotation declaration.


Thank you, Jesper Young, for answering the queries.
[ July 19, 2006: Message edited by: jaikiran pai ]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
You could access the information at runtime via reflection, for example.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Jaikiran Pai
Marshal

Joined: Jul 20, 2005
Posts: 10289
    
168

Thanks, Ilja Preuss, for answering that. I have one final question. As you said:

You could access the information at runtime via reflection


This would mean that the annotation information will be maintained as part of the class file that gets generated after compilation. I have also read that there is a "apt" tool which does the processing of the annotations in the source code(java file). So does this mean that javac internally uses apt as part of compilation, or are javac and apt two different things altogether?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14432
    
  23

JDK 5.0 includes a tool called apt (Annotation Processing Tool) which you can use to process the annotations.

You can also do it by using reflection as Ilja says, but that works only if you made sure that the annotations are retained in the class file (normally, the compiler throws away the annotations). You do this by specifying the retention policy on the annotation type declaration.

Here's an example: I've been experimenting with the following for a Swing program I'm writing. Swing has Actions. One problem with Swing Actions is that you have to write a new class for every Action, which means your program will quickly have a lot of classes that implement the Action interface. Instead of doing this, I just want to write a class with a number of methods, and each of those methods is a handler for a specific action. So I just have one class with a bunch of action handler methods instead of a whole bunch of classes (one for each action).

I wrote an annotation like this:

Note that this annotation is itself annotated with the @Retention annotation (yes, you can annotate annotations!). By specifying @Retention(RetentionPolicy.RUNTIME), the compiler will leave the annotation information in the class file, so that it is available at runtime, and I can find it using reflection.

I can now write my class with action handler methods like this:

When the application is started, I create an instance of class MyActions and lookup all the methods that are annotated with the ActionHandler annotation:

By the way, I got this idea from Hans Muller's blog, the CTO of Sun's Desktop division, who's planning to build something like this into a future version of Java (JSR-296).
Jaikiran Pai
Marshal

Joined: Jul 20, 2005
Posts: 10289
    
168

You can also do it by using reflection as Ilja says, but that works only if you made sure that the annotations are retained in the class file (normally, the compiler throws away the annotations)


That answers my question about the javac and the apt tools.

Jesper Young, thank you for that *practical* example. And thanks to everyone who helped me understand about annotations. Really appreciated.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Annotations in Java5