Target

@Target is a meta-annotation (an annotation used on other annotations) in Java that specifies the kinds of program elements to which an annotation type is applicable.It is defined in the package java.lang.annotation.Target

Why is it used?

By default, a custom annotation can be applied to any program element—classes, methods, fields, parameters, etc. The @Target annotation allows developers to restrict where their custom annotations can be used, improving code safety and clarity.

The @Target annotation takes one or more values from the ElementType enum:

Syntax

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Info {
    String author();
}Code language: CSS (css)

Simple Example

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface RunOnly {
    String createdBy();
}

public class TargetExample {

    @RunOnly(createdBy = "LotusJavaPrince")
    public void testMethod() {
        System.out.println("This method is allowed to be annotated.");
    }

    // @RunOnly(createdBy = "LotusJavaPrince") // ❌ Error if applied to class due to @Target(METHOD)
    public static void main(String[] args) {
        new TargetExample().testMethod();
    }
}

Output:

This method is allowed to be annotated.

Problem Statement:

In a security-sensitive banking application, Mahesh wants to enforce a rule that only methods (not classes or fields) can be marked with a custom annotation @Secured, which denotes privileged actions like funds transfer or loan approval. LotusJavaPrince must define this annotation with @Target(ElementType.METHOD) to enforce its use only on methods.

import java.lang.annotation.*;

// Step 1: Create annotation with specific target
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Secured {
    String role() default "USER";
}

// Step 2: Business class with secured methods
class BankingService {

    @Secured(role = "ADMIN")
    public void approveLoan() {
        System.out.println("Loan approved by ADMIN.");
    }

    @Secured(role = "MANAGER")
    public void transferFunds() {
        System.out.println("Funds transferred by MANAGER.");
    }

    public void viewBalance() {
        System.out.println("Balance viewed.");
    }
}

// Step 3: Security Auditor
public class SecurityAuditor {
    public static void main(String[] args) throws Exception {
        Class<BankingService> cls = BankingService.class;
        for (var method : cls.getDeclaredMethods()) {
            if (method.isAnnotationPresent(Secured.class)) {
                Secured secured = method.getAnnotation(Secured.class);
                System.out.println("Method: " + method.getName() +
                                   " requires role: " + secured.role());
            }
        }
    }
}

Output

Method: approveLoan requires role: ADMIN
Method: transferFunds requires role: MANAGERCode language: HTTP (http)

The @Target annotation gives developers control over annotation usage by limiting the program elements on which custom annotations can be applied. It promotes cleaner, safer, and more readable code by ensuring that annotations are only used where meaningful.

When combined with @Retention, it becomes a powerful tool in creating annotation-driven architectures commonly used in enterprise frameworks like Spring, Jakarta EE, and Hibernate.

Scroll to Top