objective-c中提供类似JAVA的反射特性,给出基本例子如下:
#import <Foundation/Foundation.h> @interface ClassA : NSObject{ int _id1; int _id2; int _id3; } @property int _id1; @property int _id2; @property int _id3; -(void) setId1:(int)id1 andId2:(int)id2 andId3:(int)id3; -(void) doMethod1; -(void) doMethod2; -(void) doMethod3; @end @implementation ClassA @synthesize _id1,_id2,_id3; -(void) setId1:(int)id1 andId2:(int)id2 andId3:(int)id3{ _id1 = id1; _id2 = id2; _id3 = id3; } -(void) doMethod1{ NSLog(@"%i", self._id1);} -(void) doMethod2{ NSLog(@"%i", self._id2);} -(void) doMethod3{ NSLog(@"%i", self._id3);} @end int main(int argc, const char * argv[]) { @autoreleasepool { Class class = NSClassFromString(@"ClassA"); //通过字符串获取CLASS NSLog(@"%@", [class className]); //打印class的名称,在oc中class是一个结构体 NSObject *tmp; SEL sel1 = @selector(doMethod2); //SEL对应选择一个方法 SEL sel2 = NSSelectorFromString(@"doMethod1"); SEL sel3 = NSSelectorFromString(@"setId1:andId2:andId3:"); tmp = [[class alloc]init]; //判断实例中是否包含这个方法,类似的还有是否属于某一个类等接口 if([tmp respondsToSelector:sel3] == YES) { //oc中反射的基本函数performSelector不支持传入基本参数,如int,以及多个参数,解决的方法有很多种, //比如可以在设计中就将参数进行封装,下面这个方法是通过NSInvocation传入参数; NSInvocation *inv = [NSInvocation invocationWithMethodSignature: [tmp methodSignatureForSelector:sel3]]; [inv setSelector:sel3]; [inv setTarget:tmp]; //arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation int input1 = 1; int input2 = 2; int input3 = 3; [inv setArgument:&(input1) atIndex:2]; //第一个参数传入 [inv setArgument:&(input2) atIndex:3]; //第二个参数传入 [inv setArgument:&(input3) atIndex:4]; //第三个参数传入 [inv invoke]; } [tmp performSelector:sel1 withObject:nil]; //执行该方法 if([tmp respondsToSelector:sel2] == YES) { [tmp performSelector:sel2 withObject:nil]; } } return 0; }
时间: 2024-10-09 23:37:53