The runtime is programmed to resemble Java-like reflection. The comparison between runtime programming and Java reflection is as follows: 1. Features that can be implemented at the same point: getting class information, property set fetching, dynamic loading of classes (nsclassfromstring (@ "ClassName")), dynamic invocation of methods
here are the related usage methods that are involved in iOS Dynamic loading of classes: nsclassfromstring (@ "ClassName"),Dynamic Invocation of the method:nsselectorformstring (@ "Dosonethingmethod:")Common methods: Iskindofclass:ismemberofclass:; Respondstoselector:; Conformstoprotocol:; Methodforselector: (Address that provides the implementation method) Format of message to object: [Receiver message] objc_msgsend (receiver,selector) objc_msgsend (receiver,selector,arg1,arg2,...) Dynamic method Solution: @dynamic PropertyName; Message forwarding: Message negotiate is responsible for forwarding-negotiate {if ([Someotherobject respondsto: @selector (Negotiate)]) return [Someo Therobject negotiate]; return self; } 2. Different points: Objective-c can dynamically add classes and methods to class, Java is not. For example:
here are the related usage methods that are involved in iOSAPI (#import <objc/runtime.h>) Class newclz =objc_allocateclasspair ([Nserror Class], "Runtimeerrorsubclass", 0); Class_addmethod (Newclz, @selector (retort), (IMP) reportfunction, "[email protected]:"); shiyongobjc_ The Allocateclasspair dynamic function creates a class and indicates the parent class and class name of the class in the parameter. The Class_addmethod function is used to add a method to the report, this method is implemented by the function reportfunction, since the function should contain at least two parameters self and _cmd, so the method has 3 parameters, the type is V, @, : (A return value, Self,_cmd). 3. In-depth comparison dynamic mechanism: OBJECTIVE-C runtime calls to class method are queried by the global name. Java VMs are through a virtual table mechanism like C + +. So objective-c can dynamically add a method to class, Java is not.
Comparison of the reflection mechanism between iOS runtime programming (runtime programming) and Java