Standard libraries

libs7Annotations

Path
pkg13libs/libs7Annotations.java
Package
pkg13libs
Study order
7
Run
Single-file source launch
Command
java pkg13libs/libs7Annotations.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg13libs/libs7Annotations.java
1package pkg13libs;2 3import java.lang.annotation.ElementType;4import java.lang.annotation.Retention;5import java.lang.annotation.RetentionPolicy;6import java.lang.annotation.Target;7import java.lang.reflect.Method;8 9/*10 * libs7Annotations.java11 * ---------------------12 * Custom annotations + processing them with reflection (mini test framework).13 *14 * DEFINITION:15 *   An annotation is metadata you attach to code. With RetentionPolicy.RUNTIME16 *   it is readable via reflection, which is how JUnit (@Test), Spring (@Component),17 *   and JPA (@Entity) discover and wire your classes.18 *19 * KEY POINTS:20 *   - @Retention controls visibility (SOURCE / CLASS / RUNTIME).21 *   - @Target restricts where it can be placed (METHOD, FIELD, TYPE, ...).22 *   - Annotations can have elements (parameters) with defaults.23 *   - Read them at runtime with getAnnotation()/isAnnotationPresent().24 */25public class libs7Annotations {26 27    // Define a custom runtime annotation with an element28    @Retention(RetentionPolicy.RUNTIME)29    @Target(ElementType.METHOD)30    @interface Test {31        String name() default "";32    }33 34    // A "test class" using our annotation35    static class CalculatorTests {36        @Test(name = "addition works")37        public void testAdd() { assertTrue(2 + 2 == 4); }38 39        @Test(name = "subtraction works")40        public void testSub() { assertTrue(5 - 3 == 2); }41 42        @Test  // intentionally failing to show the runner43        public void testBroken() { assertTrue(1 == 2); }44 45        public void notATest() { throw new RuntimeException("should never run"); }46 47        static void assertTrue(boolean cond) { if (!cond) throw new AssertionError("expected true"); }48    }49 50    public static void main(String[] args) throws Exception {51        System.out.println("Mini test runner (discovers @Test via reflection):\n");52        Object suite = new CalculatorTests();53        int pass = 0, fail = 0;54 55        for (Method m : CalculatorTests.class.getDeclaredMethods()) {56            if (!m.isAnnotationPresent(Test.class)) continue;     // only annotated methods57            Test meta = m.getAnnotation(Test.class);58            String label = meta.name().isEmpty() ? m.getName() : meta.name();59            try {60                m.invoke(suite);61                System.out.println("  PASS  " + label);62                pass++;63            } catch (Exception e) {64                System.out.println("  FAIL  " + label + "  (" + e.getCause() + ")");65                fail++;66            }67        }68        System.out.printf("%nResult: %d passed, %d failed%n", pass, fail);69    }70}