Java FAQ: Top Questions
32. What are annotations in Java?
Annotations
in Java provide metadata about code, used by the compiler, runtime, or tools. Introduced in Java 5, they are defined with
@interface
and applied with
@
.
-
Built-in Annotations:
e.g.,
@Override
,@Deprecated
,@SuppressWarnings
. - Custom Annotations: Defined for specific needs, often processed via reflection.
-
Retention:
@Retention
specifies if annotations are kept at compile-time (SOURCE
), class file (CLASS
), or runtime (RUNTIME
). -
Target:
@Target
restricts where annotations apply (e.g., methods, fields). - Use Case: Frameworks like Spring or Hibernate use annotations for configuration.