@Target is a meta-annotation used to specify the valid locations where a custom annotation can be applied. It restricts annotation usage to particular program elements such as classes, methods, fields, constructors, parameters, or other annotation types. This helps enforce correct usage and prevents annotations from being applied in inappropriate places.
Key Points: • @Target defines the program elements on which an annotation is allowed to be used. • It improves code safety and readability by preventing accidental misuse of annotations. • Multiple targets can be specified using an array of ElementType values.
Example: If an annotation is intended only for methods, using @Target(ElementType.METHOD) ensures developers cannot mistakenly apply it to classes, fields, or constructors.
Code Example:
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@interface LogExecution {
}
class EmployeeService {
@LogExecution
public void saveEmployee() {
System.out.println(
"Employee Saved");
}
}
public class Main {
public static void main(String[] args) {
EmployeeService service =
new EmployeeService();
service.saveEmployee();
}
}Interview Tip: A concise interview answer is: @Target specifies where an annotation can be applied in Java. It restricts annotation usage to specific elements such as classes, methods, fields, constructors, or parameters, helping prevent incorrect annotation placement and improving code clarity.