Reflection is a thecnical that lets us to handle object indirectly by a meta object. It is particular kind of metaprogramming.
This program concept was born from object-oriented program(OOP), on every entity is handled as classes and objects are instances
of those. So, as everything in OOP is an object, A class can be treat as an object too. This object is known as metaobject. With the
metaobject we can manipulate every feature related to that class, like its consctructor, methods, attributes, and so on.
In this post, I would like to share a little dificult that I had to use reflection concept in Qt. It is just a “HelloWorld” example.
So, lets to the example!
For this example, I just implemented person.h, person.cpp and main.cpp. Below, it is the code and some commentaries.
person.h
/* * Here, we implemented Person class. In Qt, to use reflection, it is necessary * that class inherits QObject and uses Q_OBJECT macro. The inheritance due QObject * class provides staticMetaObject member. This is the meta object for our class. * With the Q_OBJECT macro, the meta object compiler(moc) creates another C++ * source file where is implemented meta object code. */ #ifndef PERSON_H #define PERSON_H #include <QObject> class Person : public QObject { Q_OBJECT public: Q_INVOKABLE Person(QString nome); QString getName(); private: QString _name; }; #endif // PERSON_H
person.cpp
/* * Implementation of Person class. */ #include "person.h" Person::Person(QString name) { _name = name; } QString Person::getName() { return _name; }
main.cpp
/* * Main program. */ #include <QMetaObject> #include <QDebug> #include "person.h" void anyMethod(QMetaObject metaObject) { //We invoke the Person constructor through metaObject. Person *person = (Person *)metaObject .newInstance(Q_ARG(QString, QString("Sanderson"))); QString name = person->getName(); qDebug() << "Name: " << name; } int main() { //Meta object to Person class. It is not a Person instance. anyMethod(Person::staticMetaObject); return 0; }