Introspection

Introspection is the ability of a computer program to examine its own structure and properties at runtime.

Uses: 1. Runtime Type Checking. 2. Serialization (JSON/XML). 3. Unit Testing (finding test methods). 4. Dependency Injection.

        graph LR
  Center["Introspection"]:::main
  classDef main fill:#7c3aed,stroke:#8b5cf6,stroke-width:2px,color:white,font-weight:bold,rx:5,ry:5;
  classDef pre fill:#0f172a,stroke:#3b82f6,color:#94a3b8,rx:5,ry:5;
  classDef child fill:#0f172a,stroke:#10b981,color:#94a3b8,rx:5,ry:5;
  classDef related fill:#0f172a,stroke:#8b5cf6,stroke-dasharray: 5 5,color:#94a3b8,rx:5,ry:5;
  linkStyle default stroke:#4b5563,stroke-width:2px;

      

🧒 Explain Like I'm 5

Imagine if you had a magic box. Normally, you just put things in it. Introspection is like giving the box a pair of glasses and a mirror so it can look at itself and tell you, 'Hey, I'm a red box with three buttons!'. It helps the box know what it can and cannot do.

🤓 Expert Deep Dive

Technically, introspection is a subset of 'Reflective Programming'. While introspection allows a program to observe its own state (e.g., using instanceof in Java or getattr() in Python), 'Reflection' allows it to modify that state (e.g., changing the value of a private field). This is achieved by making the internal 'Symbol Tables'—which the compiler usually discards—available to the runtime environment. This is vital for 'Object-Relational Mapping' (ORM) libraries, which need to look at your classes to decide how to save them to a database. However, heavy use of introspection can lead to 'Spaghetti Code' and makes static analysis (finding bugs before running the code) much harder.

📚 Sources