Junior — Middle
Can you explain the concept of reflection in programming and how it is used?
sobes.tech AI
Answer from AI
Reflection is the ability of a program to examine and modify its structure and behavior at runtime. In programming, this means being able to dynamically obtain information about object types, methods, properties, and invoke them.
Examples of using reflection:
- Getting a list of class methods
- Calling a method by name at runtime
- Dynamically creating objects
In iOS (Swift), reflection is used, for example, for object serialization or working with dynamic data. An example in Swift:
let mirror = Mirror(reflecting: someObject)
for child in mirror.children {
print("Property name: \(child.label ?? "") value: \(child.value)")
}
This code outputs all properties of the object someObject and their values.