使用反射调用方法 [英] Calling Method using reflection
问题描述
据我所知,Swift 中的反射目前还不太可用.为了性能,我目前正在将 Objective-c 代码转换为 swift(我注意到了相当大的差异).
As I understand reflection in Swift is poorly available as of yet. I am currently in the process of converting objective-c code to swift for the sake of performance (I have noticed a considerable difference).
现在我需要的是一种使用反射调用方法的方法.需要调用该方法的对象扩展 NSObject
以允许使用以下代码解析该类;
Now what I need is a way to call a Method using reflection. The object the method needs to be called upon extends NSObject
to enable the class to be resolved using the following code;
let clazz = NSClassFromString("MyProject.DynamicClass") as NSObject.Type;
let clazzInstance = clazz() as! NSObject;
我可以使用以下代码检索参数的数量和对该方法的引用;
I am able to retrieve a the number of argument and a reference to the method using the following code;
let selectorMethod = Selector("myCustomMethod:");
let numberOfArguments : UInt32 = method_getNumberOfArguments(selectorMethod);
let referenceToMethod : Method = class_getInstanceMethod(clazz, selector!);
但是我如何使用/调用referenceToMethod
?
But how do I use/call the referenceToMethod
?
附加
我也试过调用 performSelector 但这已被 Swift 2 完全删除.我也想阻止使用任何 @objc
属性/注释.
推荐答案
如果你正在寻找一种完全 Swifty 的反射方式,那么拥有需要调用的方法的对象根本不需要是 NSObject,相反,它只需要一个必需的初始化程序.看看下面的例子:
If you are looking for a completely Swifty way of reflection, the object that has the method that needs to be called does not need to be a NSObject at all, instead all it need is a required initializer. Have a look at below example :
class A{
required init(){
}
func printSomething(s:String){
println(s)
}
}
// initializing object dynamically from class
let clazz = NSClassFromString("MyProject.A") as! A.Type
let clazzInstance = clazz()
// getting and calling its methods in Swifty way
let method = clazzInstance.printSomething
method("something")
使用它的好处在于您根本不需要使用强制转换,并且调用带有错误参数的方法会触发编译时错误
The advantage of using this stands on fact that you wont need to use casting at all and also calling method with wrong arguments would trigger a compile time error
这篇关于使用反射调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!