Standard libraries
libs6Reflection
- Path
- pkg13libs/libs6Reflection.java
- Package
- pkg13libs
- Study order
- 6
- Run
- Single-file source launch
- Command
- java pkg13libs/libs6Reflection.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg13libs;2 3import java.lang.reflect.Constructor;4import java.lang.reflect.Field;5import java.lang.reflect.Method;6import java.util.Arrays;7 8/*9 * libs6Reflection.java10 * --------------------11 * Reflection: inspecting and invoking classes/methods/fields at runtime.12 *13 * DEFINITION:14 * Reflection (java.lang.reflect) lets code examine and manipulate types it did15 * not know about at compile time. It powers frameworks (Spring, JUnit, Jackson,16 * ORMs) that wire up your classes generically.17 *18 * KEY POINTS:19 * - Class<?> is the entry point: getDeclaredFields/Methods/Constructors.20 * - setAccessible(true) bypasses access checks (use sparingly).21 * - Invoke methods/build objects dynamically with invoke()/newInstance().22 * - Trade-offs: slower, breaks encapsulation, no compile-time safety.23 */24public class libs6Reflection {25 26 static class Person {27 private String name;28 private int age;29 public Person() {}30 public Person(String name, int age) { this.name = name; this.age = age; }31 public String greet() { return "Hi, I'm " + name + " (" + age + ")"; }32 @Override public String toString() { return "Person{" + name + ", " + age + "}"; }33 }34 35 public static void main(String[] args) throws Exception {36 Class<?> clazz = Person.class;37 System.out.println("Class : " + clazz.getName());38 System.out.println("Simple name : " + clazz.getSimpleName());39 40 // Inspect fields41 System.out.println("\nFields:");42 for (Field f : clazz.getDeclaredFields())43 System.out.printf(" %s %s%n", f.getType().getSimpleName(), f.getName());44 45 // Inspect methods (declared in this class)46 System.out.println("\nMethods:");47 for (Method m : clazz.getDeclaredMethods())48 System.out.printf(" %s %s(%s)%n", m.getReturnType().getSimpleName(),49 m.getName(),50 Arrays.stream(m.getParameterTypes()).map(Class::getSimpleName).reduce((x, y) -> x + ", " + y).orElse(""));51 52 // Build an object dynamically53 Constructor<?> ctor = clazz.getConstructor(String.class, int.class);54 Object person = ctor.newInstance("Ada", 36);55 System.out.println("\nCreated : " + person);56 57 // Invoke a method dynamically58 Method greet = clazz.getMethod("greet");59 System.out.println("Invoked : " + greet.invoke(person));60 61 // Read/modify a private field (bypassing access control)62 Field nameField = clazz.getDeclaredField("name");63 nameField.setAccessible(true);64 nameField.set(person, "Grace");65 System.out.println("After set : " + person);66 }67}