Skip to content

Metadata Card

  • Prerequisites: Ch7 (OOP), Ch8 (Inheritance & Polymorphism)
  • Estimated time: 70 min
  • Core difficulty:
  • Reading mode: High focus
  • Completion marker: Can understand @Override/@Deprecated/@SuppressWarnings; can define custom annotations and read them via reflection

The Breakthrough · Tracing the Origins

Ahua sees you writing @Override on every class and asks: "What is that @ thing?" You open your mouth and realize you can't explain it.

The answer: Annotations are labels — metadata attached to code. Reflection is introspection — the program examining itself at runtime. Together they form metaprogramming — code that writes/manipulates code. Spring is built on this foundation.

Standard Annotations

java
@Override // "I confirm this overrides a parent method"
public void speak() { ... } // Compiler checks parent exists

@Deprecated // "Don't use this anymore"
public void oldMethod() { ... }

@SuppressWarnings("unchecked") // "I know what I'm doing"
public void processRawList() { ... }

Custom Annotations

java
@Target(ElementType.METHOD) // What can this be applied to?
@Retention(RetentionPolicy.RUNTIME) // How long does it live?
public @interface Loggable {
 String level() default "INFO";
 boolean includeParams() default true;
}

Reflection API

Getting class information at runtime:

java
Class<?> clazz = Class.forName("java.util.ArrayList");
Constructor<?> ctor = clazz.getConstructor();
Object list = ctor.newInstance();

Method addMethod = clazz.getMethod("add", Object.class);
addMethod.invoke(list, "reflection-added");

Key distinction: getMethods() = public (including inherited). getDeclaredMethods() = all (excluding inherited).

Annotations + Reflection = Framework Foundation

java
for (Method method : clazz.getDeclaredMethods()) {
 if (method.isAnnotationPresent(Loggable.class)) {
 Loggable log = method.getAnnotation(Loggable.class);
 // Read annotation properties, wrap method call with logging
 }
}

This is the essence of AOP (Aspect-Oriented Programming) and the basis for Spring's @Transactional, @GetMapping, @Autowired.

Final Challenge: Build a mini unit test framework. Define @Test and @BeforeEach annotations. Write a TestRunner that scans a test class, runs @BeforeEach before each @Test, and reports pass/fail counts.

Traveler's Notes

Annotations = labels for code. Reflection = runtime introspection.
@Override is a safety net for typos. @Deprecated is a polite warning.
Custom annotation = @interface + @Target + @Retention.
RUNTIME retention = readable by reflection. SOURCE = compile-time only.
Annotations + Reflection = Spring's foundation.

Built with VitePress | Software Systems Atlas