Java Annotations 101

Learn about the primary Java annotations and how to use them

🍎 If you have ever seen a Java codebase, there is a high chance you saw something like @Override or similar tags before a method or class. These tags are called Annotations. Annotations are metadata tags that help define additional information to classes, interfaces, methods, or fields. Annotations don’t add extra implementation to the functional code but help with extra information like:

  • Information for the compiler — The compiler can use annotations to catch errors or suppress warnings.
  • Information for the developer — When someone looks at the code, annotations help make it readable and easy to understand.
  • Compile-and-deployment time processing — Software tools can process annotations to generate code, XML files, etc.
  • Runtime processing — Annotations can be examined at runtime to run tests.

☕️ Java has a comprehensive list of predefined annotations to use and even lets you define your own. Here is a list of the most widely used and essential annotations.

Predefined Annotations

@Override

🏎 The @Overrideannotation informs the compiler that the subclass element is overriding the parent class or superclass element. While it is not required to use this annotation when overriding a method, it helps prevent errors. If a method marked with override fails to override a superclass method correctly, the compiler generates an error.

class Avatar {    public void destroyEvil() { ... }          // overridden method
}

class Aang extends Avatar {
@Override // overriding method
public void destroyEvil() { ... }
}

@SuppressWarnings

⚠️ Compiler warnings are helpful if you read them, but they often create noise in the terminal. @SuppressWarnings will suppress those warnings. The Java compiler can throw numerous warnings but with @SuppressWarnings, you can conceal all warnings or select the warnings you want to suppress.

@SuppressWarnings({“unchecked”, “deprecated”}) will suppress unchecked and deprecated warnings.

@SuppressWarnings("unchecked")
void uncheckedWarning() {
List words = new ArrayList();
words.add("hello"); //throws an unchecked warning
}

@deprecated

☠️ The @deprecatedannotation is also very common. It signifies that the annotated method has been deprecated and is not supported by the developers anymore. The compiler will not treat the deprecated method any different from a regular method. So even though the method is callable, it may not return the ideal response. It is documentation for developers.

@depricated
public String prepareForY2K() { ... }

@author

📝 The @author tag, a simple annotation, documents the author of the method or file. It typically gets paired with some more info like the version, release number, etc.

⭕️ Oracle recommends you should write tags in the order:

  • @author — documents the author of the code
  • @version — ensures only one update at a time(avoids locking)
  • @param — documents the name and the description of parameters
  • @return — documents the return value; omit if void
  • @throws — documents checked exceptions (declared in the throws clause)
  • @see — link or text that points to a reference
  • @since — documents the product version when the feature gets added
  • @deprecated — documents if the code is no longer supported

Test Annotations

🧑🏽‍🏫️ Writing tests is a crucial aspect of the development cycle and is as (if not more) important as writing the base code itself. There are various annotations built explicitly for tests.

@Test

🖋 @Test tells JUnit that the annotated method should be executed as a test. To run the method, JUnit constructs a new instance of the class and then invokes the test method.

You can attest two optional parameters to the annotation:

🕒 @Timeout causes a test method to fail if the execution takes longer than the designated time measured on the clock in milliseconds.

For Example, the following fails(after 0.1 seconds):

@Test(timeout=100)
public void toInfinityAndBeyond() {
while(true);
}

📣 @Expected declares that the test method must throw a specific exception, or else the test fails.

For Example, the following fails:

@Test(expected=NullPointerException.class)
public void outOfBounds(){
new ArrayList<Object>().get(1);
}

@Ignore

🤷🏽‍♀️ The @Ignore test annotation ignores a test or a group of tests to avoid a potential execution failure.

You can @Ignore tests in two possible scenarios:

  1. To ignore a test method with @Test
  2. To ignore all the tests at the class level.
@Ignore
@Test(expected=NullPointerException.class) //obviously wrong test
public void outOfBounds(){

new ArrayList<Object>().get(1);
}

@Before

⏪ Methods annotated with @Before execute before each test. It is useful when you want to execute some code before running a test, like setting up the test environment. @Before was renamed to @BeforeEach, which also works.

⏮ The sibling annotation @BeforeAll or @BeforeClass is used when an expensive operation needs to be performed before a series of tests, like starting a server or making a database change.

@After

@After is the opposite of the previous tag. All the methods annotated @After will be run after the test.

@AfterAll or @AfterClass methods are executed after all the tests of the class have been run.

All the @beforeAll and @afterall annotated methods have to be static, so they are executed before running the class’s tests.
However, @before and @after methods should not be static, else the compiler will throw an error.

public class OutputFileTest{    @BeforeAll
public static void startServer() { ... }
@Before
public void createTestLogFile() { ... }

@After
public void deleteTestLogFile() { ... }

@Test
public void test1() { ... }
@Test
public void test2() { ... }
@AfterAll
public static void stopServer() { ... }
}

The above code will execute in the order:

🟢 0️⃣ startServer() 1️⃣ createTestLogFile() 2️⃣ test1() 3️⃣ deleteTestLogFile()4️⃣ createTestLogFile() 5️⃣ test2() 6️⃣ deleteTestLogFile() 7️⃣stopServer()🔴

🍏 This list nowhere near being comprehensive, but it covers the most basic ones. Use the above examples to get a headstart on coding in Java with the best practices.

EAT🍎 SLEEP😴 DEBUG👨🏾‍💻 REPEAT🔁

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store