Fundamentals 10 min read

Understanding Java Annotations: Benefits, Types, Custom Annotation Creation, and Runtime Parsing

This article explains Java annotations, covering their advantages, common built‑in annotations, classification by lifecycle and source, meta‑annotations, how to create and apply custom annotations, and demonstrates parsing them at runtime using reflection, all illustrated with clear code examples.

Java Captain
Java Captain
Java Captain
Understanding Java Annotations: Benefits, Types, Custom Annotation Creation, and Runtime Parsing

Annotations have become an essential part of Java development, allowing developers to add metadata to code that can be processed by the compiler, tools, or at runtime. They improve code readability, reduce configuration files, and can make a programmer stand out during interviews when custom annotations are used to solve problems.

Benefits of annotations:

Help understand code written by others, especially framework code.

Replace verbose configuration with concise, clear code.

Show advanced skill when custom annotations are created and applied.

1) Common JDK annotations

JDK annotations are divided into three categories: source‑level, class‑level, and runtime annotations. Examples include @Override, @Deprecated, and @SuppressWarnings.

Example interface and implementation:

public interface people {
    public String name();
    public int age();
    public void work();
}
public class Child implements people {
    @Override
    public String name() { return null; }
    @Override
    public int age() { return 0; }
    @Override
    public void work() { }
}

If a method in the interface is commented out, the @Override annotation will cause a compile‑time error, reminding developers that the method overrides a supertype method.

The @Deprecated annotation marks a method as outdated. To suppress the warning, @SuppressWarnings("deprecation") can be used:

public class Test {
    @SuppressWarnings("deprecation")
    public void work() {
        people p = new Child();
        p.work();
    }
}

2) Third‑party annotations (e.g., Spring’s @Autowired) are mentioned but not detailed.

Annotation classification

By lifecycle:

Source annotations – exist only in source code.

Class annotations – stored in the compiled .class file.

Runtime annotations – retained at runtime and can be accessed via reflection.

By source:

JDK annotations

Third‑party annotations

Custom annotations

Meta‑annotations are annotations that describe other annotations. The most common meta‑annotations are @Target, @Retention, @Inherited, and @Documented:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description {
    String desc();
    String author();
    int age() default 18;
}

Key points about annotation members:

Allowed types include primitives, String, Class, other annotations, and enums.

If an annotation has a single member, it must be named value() and can be used without specifying the name.

An annotation without members is called a marker annotation.

Using a custom annotation

@Description(desc="i am Color", author="boy", age=18)
public String Color() {
    return "red";
}

The annotation is applied to a method because its @Target includes METHOD and TYPE.

Parsing annotations at runtime

Using reflection, a program can check whether a class or method has a specific annotation and retrieve its values:

public class ParseAnn {
    public static void main(String[] args) {
        try {
            Class c = Class.forName("com.test.Child");
            if (c.isAnnotationPresent(Description.class)) {
                Description d = (Description) c.getAnnotation(Description.class);
                System.out.println(d.value());
            }
            // Parse method annotations
            Method[] ms = c.getMethods();
            for (Method m : ms) {
                if (m.isAnnotationPresent(Description.class)) {
                    Description d1 = m.getAnnotation(Description.class);
                    System.out.println(d1.value());
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Changing the @Retention policy of Description to SOURCE or CLASS will affect whether the annotation is available at runtime for reflection.

Original article: www.jianshu.com/p/b560b30726d4

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaprogrammingCustom Annotation
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.