Java SE 11 Developer study materials
Java SE 11 Developer study resources

Java SE 11 Developer: Annotations and Functional Interfaces

Java SE 11 Developer · Work through your exam, one topic at a time.

All guide sections

Annotations and Functional Interfaces

This domain tests built-in annotation rules, how to declare and reflect on custom annotations, and the shape of functional interfaces.

Built-in annotations

@Override catches signature mistakes but is optional. @Deprecated accepts since and forRemoval (Java 9). @SuppressWarnings("unchecked") is the way to silence a warning. @SafeVarargs may be applied only to static, final or private (Java 9+) methods or constructors to promise no heap pollution from a generic varargs parameter. @FunctionalInterface is a compile-time check, not a requirement.

Meta-annotations and custom types

@Retention chooses SOURCE, CLASS (the default) or RUNTIME - only RUNTIME survives to reflection. @Target restricts where an annotation may appear; @Documented and @Inherited (classes only) complete the set, and @Repeatable allows repeats via a container annotation. An annotation type declared with @interface implicitly extends java.lang.annotation.Annotation; its elements are parameterless methods returning primitives, String, Class, enums, annotations or arrays of those, with optional default values. A single element named value may be written as @Author("me").

Functional interfaces

java.util.function supplies Supplier (get), Consumer (accept, andThen), Function (apply, compose, andThen), BiFunction, UnaryOperator, BinaryOperator, Predicate (test, and, or, negate) plus primitive specializations such as IntPredicate and ToIntFunction. A functional interface has exactly one abstract method; default and static methods do not count and neither do public Object methods such as equals.

Worked example

Declare @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface Marker { String value() default "x"; }, apply it, then read it with Method.getAnnotation(Marker.class). Reasoning: without RUNTIME retention the annotation is invisible during reflection.

Traps

Expecting CLASS retention to be reflectively visible; applying an annotation to a disallowed target (compile error); assuming a lambda can be assigned to any interface rather than one with a single abstract method.