ElementType.METHOD: Annotating Methods
What you'll learn: How to restrict your custom annotations so they can only be applied to method declarations using ElementType.METHOD.
What is METHOD Element Type?
When you create a custom annotation, ElementType.METHOD specifies that your annotation can only be placed on method declarations. This prevents accidental misuse on classes, fields, or other program elements. It's like putting a label that says "Use on methods only" on your annotation.
Think of it as a safety restriction: just like a "Fragile" sticker belongs only on packages (not on trucks or buildings), a METHOD-targeted annotation belongs only on methods.
How to Use ElementType.METHOD
You apply @Target(ElementType.METHOD) to your annotation definition:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Timed {
String unit() default "milliseconds";
}
Now @Timed can only annotate methods:
public class Service {
@Timed // Valid
public void processData() {
// implementation
}
@Timed(unit = "seconds") // Valid
public int calculate() {
return 42;
}
// @Timed // Compile error if uncommented!
// private String name;
}
Why Restrict to Methods?
Method-specific annotations are common for behaviors like logging, timing, security checks, or transaction management. By restricting with ElementType.METHOD, you get compiler protection against mistakes—trying to annotate a field or class will cause a compilation error.
Key Takeaway: Use @Target(ElementType.METHOD) to ensure your annotation can only be applied to method declarations, providing compile-time safety and clear intent about where the annotation should be used.