Quiz: Java Annotations: Built-in and Custom
Study the lesson first: Java Annotations: Built-in and Custom
Total: 7 questions
1. What are annotations in Java, who reads them and how are they written?
What are annotations in Java, who reads them and how are they written?
An annotation is metadata attached to a declaration (a class, interface, enum, record, method, constructor, field, parameter, local variable, package or module) or, since Java 8, to a type use: List<@NonEmpty String>. Annotations appeared in Java 5 (JSR 175).
An annotation does not change the code by itself. Three kinds of handlers read it: the compiler (@Override, @Deprecated), annotation processors at compile time (Lombok, MapStruct) and programs through reflection at runtime (JUnit finds methods with @Test, Spring finds beans, JPA finds entities). Without a handler an annotation does nothing.
Ways to write it:
@Override- a marker without elements, no parentheses needed;@SuppressWarnings("unchecked")- a singlevalueelement, the name can be omitted;@Deprecated(since = "9", forRemoval = true)- name = value pairs;@SuppressWarnings({"unchecked", "rawtypes"})- an array in braces; with a single element the braces are optional.
Package annotations go into package-info.java, module annotations into module-info.java. The same annotation can be put on a declaration several times only if it is declared with @Repeatable.
2. Which built-in annotations does the java.lang package contain and what does the compiler do with them?
Which built-in annotations does the java.lang package contain and what does the compiler do with them?
java.lang contains five annotations handled by javac itself:
@Override(Java 5, retentionSOURCE) - a compile error if the method overrides or implements nothing.@Deprecated(Java 5,RUNTIME) - a warning when the element is used. Since Java 9 it has thesinceandforRemovalelements: withforRemoval = truejavac reports[removal]at every call by default, while ordinary deprecation produces only a summaryNote(details with-Xlint:deprecation).@SuppressWarnings(Java 5,SOURCE) - turns off the listed warnings inside the element. Every compiler must recognize"unchecked","deprecation","removal"and"preview"; other values depend on the compiler (javac --help-lint), unknown ones are ignored. Put it on the narrowest scope, such as a local variable.@SafeVarargs(Java 7,RUNTIME) - removes unchecked warnings about generic varargs. Allowed only on constructors and onstatic,finalorprivate(since Java 9) methods; on an overridable method it is a compile error.@FunctionalInterface(Java 8,RUNTIME) - an error if the interface does not have exactly one abstract method.
3. What are meta-annotations, and how do RetentionPolicy SOURCE, CLASS and RUNTIME differ?
What are meta-annotations, and how do RetentionPolicy SOURCE, CLASS and RUNTIME differ?
Meta-annotations are annotations from java.lang.annotation that you put on the declaration of another annotation to set its properties:
@Retention- how long the annotation is kept; without it -CLASS;@Target- where it can be used (ElementType); without it - any declaration, but not a type use (List<@X String>needsTYPE_USE);@Documented- show the annotation in the generated Javadoc;@Inherited- an annotation on a class is visible on its subclasses; works for classes only, not for interfaces or methods;@Repeatable(Java 8) - the annotation can be repeated; it requires a container with avalueelement.
@Retention policies:
SOURCE- source code only, the compiler discards it. Enough for anything that works at compile time:@Override,@SuppressWarnings, processors such as Lombok.CLASS- the default: written to the .class file, but the JVM does not load it for reflection. Useful for tools that read bytecode directly.RUNTIME- available through reflection; needed by frameworks and your own handlers.
The most common mistake is a custom annotation without @Retention(RetentionPolicy.RUNTIME): the code compiles, there is no exception, but isAnnotationPresent() returns false.
4. How do you create a custom annotation in Java, and what restrictions apply to its elements?
How do you create a custom annotation in Java, and what restrictions apply to its elements?
An annotation is declared with the @interface keyword. Its elements are written as methods without parameters: the return type is the element type, and the default value follows default. Add @Retention(RetentionPolicy.RUNTIME) to read it through reflection and @Target to restrict where it can be used.
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@interface Task {
String value(); // required
Priority priority() default Priority.MEDIUM; // enum
String[] tags() default {}; // array
}
@Task("Logging") // value without a name, the rest by default
void log() {}
An annotation without elements is a marker annotation; one with a single value element is a single-element annotation. Values are read by calling the methods of the same name: task.priority().
Restrictions:
- an element type is a primitive,
String,Class(includingClass<? extends X>), an enum, another annotation or a one-dimensional array of these;Integer,Object,List, your own classes andint[][]are compile errors; - a value must be a compile-time constant;
nullis forbidden both as a value and as adefault- use an empty string, an empty array or a marker class instead; - an element has no parameters and no
throwsclause; - an annotation cannot use
extendsand cannot be generic: every annotation implicitly extends onlyjava.lang.annotation.Annotation.
5. How do you read annotations with reflection, and how do getAnnotation(), getDeclaredAnnotations() and getAnnotationsByType() differ?
How do you read annotations with reflection, and how do getAnnotation(), getDeclaredAnnotations() and getAnnotationsByType() differ?
Annotations with @Retention(RUNTIME) are read through the methods of the java.lang.reflect.AnnotatedElement interface. It is implemented by Class, Method, Field, Constructor, Parameter, Package and RecordComponent, so you look up an annotation on a class, a method or a field the same way.
getAnnotation(A.class)- the annotation ornull; takes@Inheritedinto account; for a repeatable annotation used twice or more it returnsnull(the element carries the container).isAnnotationPresent(A.class)- the same asgetAnnotation(...) != null.getAnnotations()- all annotations including inherited ones;getDeclaredAnnotations()- only those declared directly on the element.getAnnotationsByType(A.class)- an array of annotations of the type, including those inside a container; use it for repeatable annotations.Method.getParameterAnnotations()- a two-dimensional array, one array per parameter.
At runtime an annotation object is an instance of a dynamic proxy implementing the annotation interface: getClass() returns a name such as $Proxy1, so the type is obtained with annotationType(). Element values are fixed at compile time and cannot be changed at runtime.
This is how JUnit (finding methods with @Test) and Bean Validation (@NotNull, @Size on fields) work: annotations describe the rules, and reflection-based code enforces them.
6. What is an annotation processor, and what changed in JDK 23?
What is an annotation processor, and what changed in JDK 23?
An annotation processor is a subclass of javax.annotation.processing.AbstractProcessor that javac runs during compilation. It receives the elements carrying the annotations it handles (listed in @SupportedAnnotationTypes) and can report an error or a warning through the Messager, or generate new source files. Reflection plays no part, so @Retention(SOURCE) is enough for such annotations.
Lombok (@Getter, @Builder), MapStruct (DTO mappers), Dagger (dependency injection) and AutoValue (value classes) are built on processors. Benefits: mistakes show up at build time rather than at startup, and there is no reflection cost at runtime.
A processor is enabled explicitly: javac -processor TodoProcessor App.java. Since JDK 23 javac no longer runs processors found on the classpath through META-INF/services/javax.annotation.processing.Processor: unless you pass -processor, --processor-path (--processor-module-path) or -proc:full, the processor is silently skipped. JDK 21-22 only printed a warning. If Lombok stopped working after a JDK upgrade, check that it is configured as an annotation processor in Maven or Gradle.
7. When should you use an annotation, and when a marker interface, a Javadoc tag or XML configuration?
When should you use an annotation, and when a marker interface, a Javadoc tag or XML configuration?
The choice depends on who reads the mark:
- Annotation (
@Test,@Entity) - metadata for tools and frameworks. It goes on classes, methods, fields and parameters, carries parameters, and is read by the compiler, a processor or reflection. - Marker interface (
Serializable,Cloneable) - a class mark that the type system must check: it is a type, so a parameter can be declared asSerializableand checked withinstanceof. Every subclass inherits it without exception. - Javadoc tag (
@deprecated,@since) - free text for a human; it does not get into the bytecode. - External configuration (
web.xml,persistence.xml, YAML) - settings that differ between environments and change without recompiling; the code does not depend on the library.
An annotation and a marker interface are not interchangeable: an annotation can go on anything, but the compiler will not stop you from passing an unmarked object to a method, while an interface takes part in parameter types.