DeployU
Interviews / Backend Engineering / What are annotations and how do you use them in Java?

What are annotations and how do you use them in Java?

conceptual Core Concepts Interactive Quiz Code Examples

The Scenario

You are a backend engineer at a fintech company. You are building a new framework that will be used to build REST APIs.

You want to be able to add metadata to your code, such as the HTTP method and the URL path, so that you can automatically generate the API documentation.

The Challenge

Explain what annotations are in Java and how you would use them to solve this problem. What are the key benefits of using annotations?

Wrong Approach

A junior engineer might not be aware of annotations. They might try to solve this problem by using comments or a separate configuration file, which would be a less elegant and less robust solution.

Right Approach

A senior engineer would know that annotations are the perfect tool for this job. They would be able to explain what annotations are and how to use them to add metadata to code. They would also have a clear plan for how to use annotations to automatically generate the API documentation.

Step 1: Understand What Annotations Are

An annotation is a form of metadata that can be added to Java code. Annotations do not have any direct effect on the operation of the code they annotate.

Step 2: Write a Simple Annotation

Here’s how we can write a simple annotation to specify the HTTP method and the URL path of a REST API endpoint:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RequestMapping {
    String value();
    String method();
}

Step 3: Use the Annotation

We can use the annotation on a method in our controller class:

public class MyController {
    @RequestMapping(value = "/hello", method = "GET")
    public String hello() {
        return "Hello, world!";
    }
}

Step 4: Process the Annotation

We can use reflection to process the annotation at runtime and automatically generate the API documentation.

Method method = MyController.class.getMethod("hello");
RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);

System.out.println("Path: " + requestMapping.value());
System.out.println("Method: " + requestMapping.method());

The Benefits of Using Annotations

BenefitDescription
MetadataAnnotations provide a way to add metadata to code, which can be used by tools and frameworks.
ReadabilityAnnotations can make your code more readable by making it clear what the code is intended to do.
ExtensibilityYou can create your own custom annotations to add new functionality to your code.

Practice Question

You want to create a new annotation that can be used on both methods and fields. Which of the following would you use?