Annotations, Reflection, and Date/Time API
Domain 9 tests three APIs that frequently appear together: custom annotation definitions, reflective inspection, and the immutable java.time model.
Annotations
- Declare with
@interface; elements are methods, optionally withdefaultvalues. - Meta-annotations:
@Retention(SOURCE, CLASS the default, RUNTIME),@Target(METHOD, FIELD, TYPE, and others),@Inherited(class annotations only),@Repeatable,@Documented. - Only
RUNTIMEretention is visible to reflection throughclazz.getAnnotation(MyAnno.class).
Reflection
- Access a
Class<?>viaobj.getClass(),Type.class, orClass.forName("fq.Name"). getMethods()returns public methods including inherited ones;getDeclaredMethods()returns all methods declared on the class but none inherited.setAccessible(true)bypasses access checks only when the owning module opens the package.- Invoking a method that throws wraps the cause in
InvocationTargetException; unwrap withgetCause().
Date-Time
LocalDate,LocalTimeandLocalDateTimeare zone-free and immutable;ZonedDateTimeandOffsetDateTimecarry a zone or offset;Instantis a UTC point on the timeline.Durationis time-based (hours, seconds, nanos),Periodis date-based (years, months, days). Both providebetween().- All
plus,minusandwithmethods return new objects.DateTimeFormatteris immutable and thread-safe, unlikeSimpleDateFormat. ZonedDateTimeresolves daylight-saving gaps and overlaps using zone rules.
Worked example
LocalDate d = LocalDate.of(2024, 2, 28);
LocalDate e = d.plusDays(1); // 2024-02-29, a leap year
Period p = Period.between(d, e); // P1D
d is unchanged; plusDays returns a new instance, and leap-year handling is automatic.
Traps
LocalDateTime.now()ignores the zone; useZonedDateTime.now()for zone-aware values.Duration.betweenon twoLocalDatevalues compiles but throwsUnsupportedTemporalTypeExceptionat runtime; usePeriod.@Retention(SOURCE)annotations vanish from bytecode entirely.