objective-c中提供相似JAVA的反射特性,給出基本例子以下:objective-c
#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; }