Java - Annotations and Reflection in Java

1. What are Annotations?

Annotations in Java are special markers added to code that provide metadata (information about the program) to the compiler or runtime. They do not directly change how the program runs, but they help tools, frameworks, or the compiler understand how the code should be handled.

Annotations are written using the @ symbol.

Examples:

  • @Override

  • @Deprecated

  • @SuppressWarnings

Example usage:

class Demo { @Override public String toString() { return "Example"; } }

This tells the compiler that the method overrides a superclass method.


2. Why Use Annotations?

  • Provide additional information to the compiler

  • Reduce boilerplate code

  • Help frameworks automate tasks

  • Improve readability and maintainability

Annotations are widely used in modern Java frameworks.


3. Creating Custom Annotations

@interface MyAnnotation { String value(); }

Using it:

@MyAnnotation(value="Test") class Sample { }

Annotations can include elements such as values or parameters.


4. What is Reflection?

Reflection is a feature in Java that allows a program to inspect and manipulate its own structure during runtime. Using reflection, a program can examine classes, methods, constructors, and fields even if their names are not known at compile time.

It is part of the java.lang.reflect package.


5. Uses of Reflection

  • Inspect class details dynamically

  • Create objects at runtime

  • Access private fields or methods

  • Support frameworks and libraries

Reflection is commonly used in testing tools and dependency injection frameworks.


6. Simple Reflection Example

import java.lang.reflect.Method; class Test { public void display() { System.out.println("Hello"); } } public class Demo { public static void main(String[] args) throws Exception { Class c = Test.class; Method m = c.getMethod("display"); Test obj = new Test(); m.invoke(obj); } }

This program calls a method dynamically using reflection.


7. Advantages and Limitations

Advantages:

  • Powerful runtime inspection

  • Flexible and dynamic programming

  • Useful for frameworks and libraries

Limitations:

  • Slower performance

  • Can break encapsulation

  • Harder to debug and maintain


Summary

Annotations provide metadata that helps tools and frameworks process code more effectively, while reflection enables programs to inspect and manipulate their structure at runtime. Together, they support advanced and flexible Java programming techniques.