Question

What is the purpose of annotations in Java? I have this fuzzy idea of them as somewhere in between a comment and actual code. Do they affect the program at run time?

What are their typical usages?

Are they unique to Java? Is there a C++ equivalent?

Was it helpful?

Solution

Annotations are primarily used by code that is inspecting other code. They are often used for modifying (i.e. decorating or wrapping) existing classes at run-time to change their behavior. Frameworks such as JUnit and Hibernate use annotations to minimize the amount of code you need to write yourself to use the frameworks.

Oracle has a good explanation of the concept and its meaning in Java on their site.

OTHER TIPS

Also, are they unique to Java, is there a C++ equivalent?

No, but VB and C# have attributes which are the same thing.

Their use is quite diverse. One typical Java example, @Override has no effect on the code but it can be used by the compiler to generate a warning (or error) if the decorated method doesn't actually override another method. Similarly, methods can be marked obsolete.

Then there's reflection. When you reflect a type of a class in your code, you can access the attributes and act according to the information found there. I don't know any examples in Java but in .NET this is used by the compiler to generate (de)serialization information for classes, determine the memory layout of structures and declare function imports from legacy libraries (among others). They also control how the IDE form designer works.

/EDIT: Attributes on classes are comparable to tag interfaces (like Serializable in Java). However, the .NET coding guidelines say not to use tag interfaces. Also, they only work on class level, not on method level.

Anders gives a good summary, and here's an example of a JUnit annotation

@Test(expected=IOException.class)
public void flatfileMissing() throws IOException {
    readFlatFile("testfiles"+separator+"flatfile_doesnotexist.dat");
}

Here the @Test annotation is telling JUnit that the flatfileMissing method is a test that should be executed and that the expected result is a thrown IOException. Thus, when you run your tests, this method will be called and the test will pass or fail based on whether an IOException is thrown.

Java also has the Annotation Processing Tool (apt) where not only you create annotations, but decide also how do these annotations work on the source code.

Here is an introduction.

To see some cool stuff you can do with Annotations, check out my JavaBean annotations and annotation processor.

They're great for generating code, adding extra validations during your build, and I've also been using them for an error message framework (not yet published -- need to clear with the bosses...).

By literal definition an annotation adds notes to an element. Likewise, Java annotations are tags that we insert into source code for providing more information about the code. Java annotations associate information with the annotated program element. Beside Java annotations Java programs have copious amounts of informal documentation that typically is contained within comments in the source code file. But, Java annotations are different from comments they annotate the program elements directly using annotation types to describe the form of the annotations. Java Annotations present the information in a standard and structured way so that it could be used amenably by processing tools.

To read in detail, there is a nice tutorial on Java Annotations

When do you use Java's @Override annotation and why? The link refers to a question on when one should use the override annotation(@override).. This might help understand the concept of annotation better.Check out.

Annotations when it comes to EJB is known as choosing Implicit middle-ware approach over an explicit middle-ware approach , when you use annotation you're customizing what you exactly need from the API for example you need to call transaction method for a bank transfer : without using annotation : the code will be

transfer(Account account1, Account account2, long amount)    
{
   // 1: Call middleware API to perform a security check
   // 2: Call middleware API to start a transaction
   // 3: Call middleware API to load rows from the database
   // 4: Subtract the balance from one account, add to the other
   // 5: Call middleware API to store rows in the database
   // 6: Call middleware API to end the transaction
}

while using Annotation your code contains no cumbersome API calls to use the middle- ware services. The code is clean and focused on business logic

transfer(Account account1, Account account2, long amount) 
{
   // 1: Subtract the balance from one account, add to the other
}

Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.

Annotations have a number of uses, among them:

  • Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
  • Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
  • Runtime processing — Some annotations are available to be examined at runtime.

The visibility scope is defined by java.lang.annotation.RetentionPolicy constants SOURCE, CLASS, and RUNTIME

  • RetentionPolicy.SOURCE: The annotation would be available in the source code of the program and can be used by the compiler or apt for code generation.
  • RetentionPolicy.CLASS: The annotation would be in the .class file but it would not be available at runtime. Used by byte code manipulation tools such as ASM perform the modifications
  • RetentionPolicy.RUNTIME: The annotation would be available at .class file and runtime, for inspection via java reflection via getAnnotations().
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top