Reflection = kiểm tra và thao tác class/method/field lúc runtime, không cần biết tên class lúc compile.
Class<?> cls = Class.forName("com.example.User");
Object obj = cls.getDeclaredConstructor().newInstance();
Method m = cls.getDeclaredMethod("setName", String.class);
m.setAccessible(true); // bypass private
m.invoke(obj, "Ada");
Field f = cls.getDeclaredField("name");
f.setAccessible(true);
String name = (String) f.get(obj);Use case chính (đều là framework, không phải code app thông thường):
- DI container: Spring inject bean qua reflection.
- ORM: Hibernate map row DB → entity field qua reflection.
- Serialization: Jackson, Gson đọc/ghi field qua reflection.
- Mocking: Mockito tạo proxy qua reflection.
- Annotation processing.
Chi phí:
- Hiệu năng: chậm hơn direct call ~10-100x (JIT khó optimize).
- Type safety: mất check compile-time.
- Module system (Java 9+): muốn reflect class trong module khác → cần --add-opens.
Tránh trong code app thông thường. Hiện đại: dùng bytecode generation (ByteBuddy, ASM), APT (annotation processor sinh code lúc compile), hoặc records + sealed type cho serialization.