Junior — Middle
How to identify an annotation that applies exclusively to classes?
sobes.tech AI
Answer from AI
To define an annotation in Java that applies only to classes, you should use the meta-annotation @Target with the parameter ElementType.TYPE. This restricts the annotation's scope to classes, interfaces, enums, and annotations.
Example of defining such an annotation:
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Target(ElementType.TYPE) // applicable only to classes, interfaces, enums, and annotations
@Retention(RetentionPolicy.RUNTIME) // available at runtime
public @interface MyClassAnnotation {
String value() default "";
}
Now, @MyClassAnnotation can only be placed above class, interface, or enum declarations, but not on methods or fields.