Java Custom Annotations - Interview Questions & Answers

Master Java Custom Annotations with interview-focused questions and answers. Learn how to create custom annotations, use @Target and @Retention, define annotation attributes, and understand their role in Spring Boot and enterprise applications.


Introduction

Java provides several built-in annotations such as @Override and @Deprecated, but developers can also create their own annotations.

Custom annotations are widely used in enterprise applications for:

  • Logging
  • Auditing
  • Validation
  • Security
  • Transaction Management
  • Performance Monitoring
  • Custom Framework Development

Spring Boot itself heavily relies on custom annotations like @Service, @Repository, @RestController, and @Transactional.


Why Interviewers Ask About Custom Annotations?

Interviewers want to evaluate whether you understand:

  • Annotation creation
  • Annotation metadata
  • Reflection
  • Framework internals
  • Spring Boot architecture

A developer who understands custom annotations usually has a deeper understanding of how Java frameworks work internally.

flowchart LR

Developer --> CustomAnnotation

CustomAnnotation --> Compiler

Compiler --> JVM

JVM --> Reflection

Reflection --> Framework

Framework --> BusinessApplication

Interview Question 1

What is a Custom Annotation?

Answer

A Custom Annotation is an annotation created by developers using the @interface keyword.

It allows developers to attach custom metadata to:

  • Classes
  • Methods
  • Fields
  • Constructors
  • Parameters

Unlike built-in annotations, custom annotations solve business-specific requirements.


Java Example

public @interface Audit {

}

Usage

@Audit
public class PaymentService {

}

Diagram

flowchart LR

Developer --> "@interface"

"@interface" --> CustomAnnotation

CustomAnnotation --> JavaClass

Interview Tip

Remember:

Annotations do not execute business logic themselves. They only provide metadata that can later be processed by the compiler, JVM, or frameworks.


Interview Question 2

How do you create a Custom Annotation?

Answer

Custom annotations are created using the @interface keyword.

A production-ready custom annotation usually contains:

  • @Target
  • @Retention
  • Annotation attributes

Java Example

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Audit {

}

Now it can be used as:

public class PaymentService {

    @Audit
    public void transferMoney() {

    }

}

Diagram

flowchart TD

@Target --> CustomAnnotation

@Retention --> CustomAnnotation

CustomAnnotation --> BusinessMethod

Interview Tip

Every custom annotation should explicitly define:

  • Where it can be used (@Target)
  • How long it should exist (@Retention)

Interview Question 3

What is the @interface Keyword?

Answer

The @interface keyword is a Java language construct used to define annotations.

Although it resembles an interface, it is not a normal Java interface.

Example:

public @interface LogExecution {

}

This creates a new annotation named LogExecution.


Diagram

flowchart LR

Interface --> Methods

Annotation --> Metadata

Metadata --> Framework

Interview Tip

A common interview question is:

Is an annotation an interface?

Answer:

No.

It is declared using @interface, but internally the compiler generates a special interface that extends java.lang.annotation.Annotation.


Interview Question 4

What are @Target and @Retention?

Answer

These are Meta Annotations used to control the behavior of custom annotations.

@Target

Defines where the annotation can be used.

Examples:

  • Class
  • Method
  • Field
  • Constructor
  • Parameter

@Retention

Defines how long the annotation is available.

Possible values:

  • SOURCE
  • CLASS
  • RUNTIME

Java Example

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EntityInfo {

}

Diagram

flowchart LR

@Target --> UsageLocation

@Retention --> AnnotationLifecycle

UsageLocation --> Annotation

AnnotationLifecycle --> Annotation

Interview Tip

Spring Boot annotations use RetentionPolicy.RUNTIME because Spring discovers them using Reflection.


Interview Question 5

How do you define attributes in a Custom Annotation?

Answer

Annotations can contain attributes, which behave like methods without implementation.

Example:

public @interface Audit {

    String module();

    String owner();

}

Usage:

@Audit(
    module = "Payment",
    owner = "Finance Team"
)
public void transferMoney() {

}

You can also define default values.

public @interface Audit {

    String module();

    String owner() default "Admin";

}

Diagram

flowchart LR

Annotation --> Attribute1["module()"]

Annotation --> Attribute2["owner()"]

Attribute1 --> AnnotationUsage

Attribute2 --> AnnotationUsage

Interview Tip

Annotation attributes:

  • Cannot have method bodies
  • Cannot accept arbitrary object types
  • Typically use primitive types, String, Class, Enum, arrays, or other annotations


Interview Question 6

How do you read a Custom Annotation using Reflection?

Answer

Reflection allows Java programs to inspect classes, methods, fields, and annotations at runtime.

This is how frameworks like Spring Boot, Hibernate, and JUnit discover annotations.


Java Example

import java.lang.reflect.Method;

public class Main {

    public static void main(String[] args) throws Exception {

        Method method = PaymentService.class
                .getMethod("transferMoney");

        Audit audit = method.getAnnotation(Audit.class);

        System.out.println(audit.module());

    }

}

Output

Payment

Diagram

flowchart LR

JavaClass --> Reflection

Reflection --> ReadAnnotation

ReadAnnotation --> ExecuteLogic

Interview Tip

Reflection can only read annotations that use:

@Retention(RetentionPolicy.RUNTIME)

Interview Question 7

How does Spring Boot use Custom Annotations internally?

Answer

Spring Boot scans all classes during application startup.

It uses Reflection to identify annotations such as:

  • @Component
  • @Service
  • @Repository
  • @Controller
  • @Transactional

After finding these annotations, Spring creates and manages objects inside the IoC Container.


Diagram

flowchart LR

ApplicationStart --> ComponentScan

ComponentScan --> Reflection

Reflection --> "@Service"

Reflection --> "@Repository"

Reflection --> "@Controller"

Reflection --> IoCContainer

IoCContainer --> DependencyInjection

Java Example

@Service
public class CustomerService {

}

Spring discovers this annotation during startup and automatically creates the bean.


Interview Tip

A common interview question is:

How does Spring know which classes are beans?

Answer:

  • Component Scanning
  • Reflection
  • Runtime Annotations

Interview Question 8

What are the real-world use cases of Custom Annotations?

Answer

Enterprise applications use custom annotations for many cross-cutting concerns.

Examples include:

  • Audit Logging
  • Security
  • Validation
  • Authorization
  • Performance Monitoring
  • API Rate Limiting
  • Exception Handling
  • Caching

Example

@Audit(module = "Payments")
public void transferMoney() {

}

An Aspect (AOP) can intercept this annotation and automatically write audit logs.


Diagram

flowchart TD

BusinessMethod --> CustomAnnotation

CustomAnnotation --> SpringAOP

SpringAOP --> Logging

SpringAOP --> Security

SpringAOP --> Monitoring

Interview Tip

Mention Spring AOP when discussing custom annotations.

It demonstrates enterprise-level understanding.


Interview Question 9

What are the common mistakes when creating Custom Annotations?

Answer

Avoid these mistakes:

❌ Forgetting @Retention(RUNTIME)

❌ Missing @Target

❌ Using Reflection unnecessarily

❌ Creating too many custom annotations

❌ Embedding business logic inside annotations

❌ Poor annotation naming


Diagram

flowchart TD

Mistakes --> MissingRetention

Mistakes --> MissingTarget

Mistakes --> TooManyAnnotations

Mistakes --> ReflectionOveruse

Mistakes --> BusinessLogicInAnnotation

Interview Tip

Annotations should contain metadata only.

Business logic belongs in services, interceptors, or aspects.


Interview Question 10

What are the best practices for designing Custom Annotations?

Answer

Follow these best practices:

  • Use meaningful names.
  • Keep annotations lightweight.
  • Always specify @Target.
  • Always specify @Retention.
  • Use RUNTIME only when Reflection is required.
  • Keep annotation attributes simple.
  • Document custom annotations.
  • Combine annotations with Spring AOP when implementing cross-cutting concerns.

Good Example

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Audit {

    String module();

}

Diagram

flowchart LR

GoodAnnotation --> ClearName

GoodAnnotation --> Target

GoodAnnotation --> Retention

GoodAnnotation --> Documentation

GoodAnnotation --> SpringAOP

Common Interview Mistakes

  • Confusing annotations with interfaces.
  • Assuming annotations execute business logic.
  • Forgetting RetentionPolicy.RUNTIME.
  • Using Reflection for compile-time annotations.
  • Missing @Target.
  • Creating annotations for simple configuration values.
  • Ignoring performance when scanning many classes.

Quick Revision

Concept Key Point
Custom Annotation Developer-defined metadata
@interface Creates an annotation
@Target Defines where annotation can be used
@Retention Defines annotation lifecycle
Reflection Reads runtime annotations
Spring Boot Uses Reflection + Component Scanning
Spring AOP Processes many custom annotations
Enterprise Usage Logging, Security, Validation, Auditing
Common Mistake Missing RetentionPolicy.RUNTIME
Best Practice Keep annotations simple and metadata-focused

Interviewer's Expectations

Junior Java Developer

  • Create a basic custom annotation.
  • Explain @Target and @Retention.
  • Use annotations correctly.

Senior Java Developer

  • Explain runtime processing.
  • Read annotations using Reflection.
  • Describe Spring's annotation scanning.
  • Discuss annotation lifecycle.

Solution Architect

  • Explain how frameworks use annotations.
  • Discuss performance considerations of Reflection.
  • Design reusable custom annotations.
  • Combine annotations with AOP and framework extensions.

Related Interview Questions

  • What are Meta Annotations?
  • Explain @Retention in detail.
  • Explain @Target in detail.
  • What is Reflection?
  • How does Spring IoC work?
  • How does Component Scanning work?
  • What is Spring AOP?
  • Difference between @Component, @Service, and @Repository?
  • How does @Transactional work internally?
  • What are Annotation Processors?

Summary

Custom Annotations allow developers to add meaningful metadata to Java code without changing business logic. Combined with Reflection and Spring AOP, they enable powerful framework features such as dependency injection, transaction management, auditing, validation, logging, and security.

For interviews, don't stop at explaining how to create an annotation. Show that you understand how it is processed, how Spring Boot discovers it, and where it is used in real enterprise applications. This depth of knowledge is what interviewers look for in senior Java developers and solution architects.