由于 Java 开发人员有时习惯使用这种方法:
// init
Map<Class, Handler> map = new HashMap<Class, Handler>;
map.put(MyClass1.class, new Handler1());
map.put(MyClass2.class, new Handler2());
// later
Handler handler = map.get(currentObject.getClass());
handler.handle();
Objective-c中有类似的方法吗?
PS。我知道这可能可以用另一种方式解决:MyClass 可以返回 Handler 实例(基本方法并在继承者中重写),但这不好,因为 MyClassN 不知道 Handler 并且可以在运行时解析它。最佳答案
在 Objective-C 中执行此操作的惯用方法是在 Categories 中定义方法。 ,而不是使用反射。
类别允许您“从外部”向类添加方法,并像使用该方法一样使用该方法。 Java中没有类似的机制,所以需要使用反射来弥补。
// For separate testing you can put handlers in a separate class
@interface Handlers
+(void)handler1;
+(void)handler2;
@end
// Below is the mapping code. It goes in a separate file
@interface MyClass1 (Handler)
-(void)handleMessage;
@end
@implementation MyClass1
-(void)handleMessage {
[Handlers handler1];
}
@end
@interface MyClass2 (Handler)
-(void)handleMessage;
@end
@implementation MyClass2
-(void)handleMessage {
[Handlers handler2];
}
@end
此设置允许您在 MyClass1
和 MyClass2
的对象上调用 handleMessage
,并且运行时将正确地将消息分派(dispatch)到正确的方法:
id someObject = ... // <<== Set an object of MyClass1 or MyClass2
[someObject handleMessage]; // Calls the right method, even though the classes themselves do not declare it
如果您使用此设置,您可以与类别分开测试处理程序方法,这些方法提供“粘合逻辑”(与您的 Java Map
的方式相同),但不参与消息的实际“有效负载”处理。
关于java - 在 Objective-c 中使用反射进行映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23858975/