ProgrammingBackend Developer

Explain how annotation support is implemented in Java and how to create your own custom annotations. How to use them correctly in practice?

Pass interviews with Hintsage AI assistant

Answer.

History of the issue:

Annotations appeared in Java 5 to add metadata to the bytecode without changing the actual logic of the program. Annotations allow for easily supplying classes and methods with additional information for frameworks, compilers, or parsers.

Problem:

Poorly designed or improperly used annotations lead to complications in code maintenance. Sometimes developers confuse the applicability of annotations or do not understand how to create their own, and are unaware of the possibility to create annotations with parameters.

Solution:

Creating a custom annotation:

import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyTest { String value() default ""; }

Using the annotation:

public class TestClass { @MyTest("Example") public void testMethod() {...} }

Key features:

  • Annotations can have parameters with default values
  • The annotation must be accompanied by meta-annotations @Target and @Retention
  • Using Runtime Retention allows the annotation to be used via Reflection

Tricky questions.

Can an annotation inherit from another annotation?

Answer: No, annotations in Java do not support inheritance from one another.

Is it possible to make the annotation’s work mandatory in all subclasses of a class?

Answer: Not directly. You need to additionally check for the presence of the annotation via reflection, manually implementing similar control.

What is the difference between @Retention(CLASS) and @Retention(RUNTIME)?

Answer:

  • @Retention(RUNTIME): the annotation is available during runtime via reflection
  • @Retention(CLASS): the annotation is stored in the bytecode but is not available via Reflection (only used by the compiler)

Common mistakes and anti-patterns

  • Not specifying @Target and @Retention for your annotations
  • Using annotations for unintended purposes (e.g., processing them with the wrong tools or outside the intended environment)

Real-life examples

Negative case

In a project, they decided to replace XML configuration with annotations, but didn’t add @Retention(RUNTIME)

Pros:

  • The code became more compact

Cons:

  • Annotations are not visible at runtime, the framework cannot process them

Positive case

Configured a custom annotation @Audit on methods, controlling the audit of business operations, with reflection of the actual logic call on the server.

Pros:

  • Centralized, transparent audit

Cons:

  • Processing annotations requires a small runtime overhead and thoughtful exception handling for cycles