反射, 在我看来 就是 运行时把字符串映射为类.
我不是很专业, 还望各位大佬嘴下留情.....
参考 https://blog.csdn.net/kenier/article/details/62041312
https://blog.csdn.net/liulong1567/article/details/45273017
第一种方式:
//
class TestReflection : public QObject
{
Q_OBJECT
public:
//此处必须使用 Q_INVOKABLE
Q_INVOKABLE explicit TestReflection(QObject *parent = nullptr):QObject(parent)
{
m_name.clear();
}
Q_INVOKABLE QString name() const
{
return m_name;
}
private:
QString m_name;
};
//调用
qRegisterMetaType<TestReflection*>();
int type = QMetaType::type("TestReflection*");
const QMetaObject *metaObj = QMetaType::metaObjectForType(type);
QObject *obj = metaObj->newInstance(Q_ARG(QString, QStringLiteral("Reflection")),
Q_ARG(QObject*, nullptr));
TestReflection *test = qobject_cast<TestReflection*>(obj);
QString retVal;
QMetaObject::invokeMethod(test, "name", Qt::DirectConnection,
Q_RETURN_ARG(QString, retVal));
qDebug() << "result: " << retVal;
第二种方式:
//
#include <QObject>
#include <QtDebug>
#include <QByteArray>
#include <QMetaObject>
#include <QHash>
class A : public QObject
{
Q_OBJECT
public:
A(QObject *p) : QObject(p)
{
qDebug() << Q_FUNC_INFO;
}
Q_INVOKABLE void name()
{
qDebug() << Q_FUNC_INFO;
}
};
//
class ObjectFactory
{
public:
template<typename T> static void registerClass()
{
qDebug() << "class name: [" << typeid(T).name() << "]";
constructors().insert( T::staticMetaObject.className(), &constructorHelper<T> );
}
static QObject* createObject( const QByteArray& className,
QObject* parent = nullptr )
{
Constructor constructor = constructors().value( className );
if ( constructor == nullptr )
return nullptr;
return (*constructor)( parent );
}
private:
typedef QObject* (*Constructor)( QObject* parent );
template<typename T> static QObject* constructorHelper( QObject* parent )
{
return new T( parent );
}
static QHash<QByteArray, Constructor>& constructors()
{
static QHash<QByteArray, Constructor> instance;
return instance;
}
};
//调用
ObjectFactory::registerClass<A>();
A* object = (A*)ObjectFactory::createObject( "A" );
if(object)
{
QMetaObject::invokeMethod(object, "name", Qt::DirectConnection);
}