In Java we can instantiate an object (knowing only the parameters types) dynamically like this:
Class<?> msgClass = Class.forName(className);
constructor = msgClass.getConstructor(String.class, String.class, String.class);
MyClass myClass = (MyClass) constructor.newInstance(myString, myString2, myString3);
public class MyClass {
public MyClass(String s, String s2, String s2){}
}
Is there a way to do the same in objective-c, knowing only the parameters types to be passed in to the objective-c class constructor.
Thanks in advance.
Yes, depending on what you’re really doing. ObjC doesn’t have language-level “constructors” in the same way– there are
initmethods which usually called alongside theallocinstantiation method, but note thatinitis there by framework convention and not by spec, so the runtime doesn’t “know” what “constructor” you’d want to call.You can instantiate an object (the equivalent of allocating it) like this:
although you might as well do it more directly:
But then you’d still need to call whatever
initmethod you want on it. If you don’t want to do this directly, you need to know the selector for the method so you can send the object the correct message. The selector is a static representation of the message signature. You could invoke that method through the runtime API like this:ObjC runtime reference: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html