Does NSClassFromString from iOS have an equivalent in the BlackBerry 10 SDK?
-
C++ is not a language that uses a runtime, so it has no equivalent. – borrrden Feb 05 '13 at 15:07
-
There are very few cases when you really need this method. Probably you should redesign the app to avoid this method at all. – Sulthan Feb 05 '13 at 17:04
-
1Voting to reopen - Just because the answer is 'no' doesn't make this less of a question. – Michael Donohue Feb 05 '13 at 18:00
-
There is a *yes* answer. See below. – Codo Feb 09 '13 at 14:07
2 Answers
You cannot do this natively in C++, C++ is a fairly static language that does not have the runtime capabilities that Objective-C has. It is possible, with a bit of hard graft, if you map all your Class names with instances, using the template mechanism. This is described in "Is there a way to instantiate objects from a string holding their class name? ".
As for the BB10 SDK, based on the assumption that it's Java, this is possible.
Class myClassName = Class.forName("ClassName");
ClassName myInstance = myClassName.newInstance();
Update: BB10 SDK is C++, as such there isn't a native way to do this, except what is mentioned above.
-
1BB10 is actually C++ based. It can run Android applications but its native language is C++. – Sulthan Feb 05 '13 at 17:02
Yes, there is an equivalent to NSClassFromString
provided you use the Qt meta type system.
You'll need to use to Q_DECLARE_METATYPE
macro and qRegisterMetaType
:
class UserClass : public Superclass {
...
}
Q_DECLARE_METATYPE(UserClass)
int main(int argc, char *argv[]) {
qRegisterMetaType<UserClass>("UserClass");
....
}
Then you can create an instance of your class with the following code:
int id = QMetaType::type("UserClass");
UserClass *instance = (UserClass*)(QMetaType::construct(id));
I guess this approach to create objects is used by QML as well, e.g. in the attachedObjects section.

- 75,595
- 17
- 168
- 206