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.
Reflection = inspect and manipulate classes/methods/fields at runtime, without knowing the class name at compile time.
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);Main use cases (frameworks, not typical app code):
- DI containers: Spring injects beans via reflection.
- ORMs: Hibernate maps DB rows → entity fields via reflection.
- Serialization: Jackson, Gson read/write fields via reflection.
- Mocking: Mockito creates proxies via reflection.
- Annotation processing.
Costs:
- Performance: ~10-100x slower than direct calls (JIT struggles to optimise).
- Type safety: loses compile-time checks.
- Module system (Java 9+): reflecting a class in another module needs --add-opens.
Avoid in typical app code. Modern alternatives: bytecode generation (ByteBuddy, ASM), APT (annotation processors generating code at compile time), or records + sealed types for serialization.