代码改变世界

objective-C 中如何判断一个类中有没有定义某个方法

2012-08-13 17:07  java环境变量  阅读(279)  评论(0编辑  收藏  举报


C#中可以通过反射分析元数据来解决这个问题,示例代码如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Reflection;
 
namespace Hello
{
    class Program
    {
        static void Main(string[] args)
        {
            if (IsMethodDefined(typeof(Utils), "HelloWorld"))
            {
                Console.WriteLine("Utils类中有方法HelloWorld");
            }
            else
            {
                Console.WriteLine("Utils类中没有方法HelloWorld");
            }
            Console.ReadKey();
        }    
        /// <summary>
        /// 判断一个类中有无"指定名称"的方法
        /// </summary>
        /// <param name="type"></param>
        /// <param name="methodName"></param>
        /// <returns></returns>
        static bool IsMethodDefined(Type type,string methodName)
        {
            bool result = false;
            foreach (MemberInfo m in type.GetMembers())
            {
                if (m.Name == methodName)
                {
                    result = true;
                    break;
                }
            }
            return result;
        }
    }
 
    public static class Utils
    {
        public static void HelloWorld()
        {
            Console.WriteLine("Hello World!");
        }
    }
}

在obj-C中,则是通过选择器selector来判断的

Sampe.h

#import <Foundation/Foundation.h>
@interface Sample : NSObject {
}
-(void) print:(NSString*) msg;
@end

Sample.m

#import "Sample.h"
@implementation Sample
-(void) print:(NSString*) msg
{
	NSLog(@"%@",msg);
}
@end

main函数:

#import <Foundation/Foundation.h>
#import "Sample.h"

int main (int argc, const char * argv[]) {
    
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
	Sample *s = [Sample new];	
	
	if ([s respondsToSelector:@selector(print:)]) //这一行就是判断实例s中有没有方法print
	{
		[s print:@"Hello World"];
	}
	else
	{
		NSLog(@"%@",@"Sample类中没有定义方法print");
	}
	
	[s release];
	
    [pool drain];
    return 0;
}