Qt-meat-Object

Source: Internet
Author: User

Java reflection mechanisms are widely used in various popular open-source frameworks today. As long as you open the source code of spring, struts, Or hibernate, you can find the reflection of Java. Using Reflection, we can obtain the types of various objects through strings in the system runtime. Then we can instantiate objects and call related methods of objects through types. Of course, this is very simple and easy to understand for Java. Because Java has virtual machines, the runtime system is like an object-type database. We only need to provide query conditions, we can return the required object type. The following Java code demonstrates how to apply the reflect feature:

package org.storevm; importjava.lang.reflect.Field; importjava.lang.reflect.Method; publicclass MyClass {     private String name;     public MyClass() {     }     publicvoid say() {         System.out.println(name);     }     public String getName() {         returnname;     }     publicvoid setName(String name) {         this.name = name;     }     publicstaticvoid main(String[] args) throws Exception {         Class clazz = Class.forName("org.storevm.MyClass");         Object obj = clazz.newInstance();         Field field = clazz.getDeclaredField("name");         field.setAccessible(true);         field.set(obj, "jacktan");         Method method = clazz.getMethod("say", new Class[] {});         method.invoke(obj, new Object[] {});     } }

The functions of the above Code are:

1. Use the string "org. storevm. myclass" to obtain the type object;

2. instantiate a type object as a myclass object;

3. Get the name attribute from the type object and set it to read/write status;

4. Set the value of the name attribute to a "jacktan" string;

5. Get the say method object from the type object;

6. Call the say method of the myclass object;

Using Java reflection, we can complete all functional operations on the myclass object without referencing the myclass object instance.

C ++ does not have a strong introspection function, but the QT framework extends a powerful introspection mechanism similar to Java reflection for C ++, which is called "meta-object ". Through this system, we can easily implement the functions implemented in the above Java. However, compared with qt c ++, the encoding is more complex and the code is not very readable. For Java developers, they may not be familiar with it. The following code demonstrates the features of implementing introspection in qt c ++:

Header file: cresultset. h

 

# Ifndefcresultset_h # definecresultset_h # include <qobject> # include <qstring> classcresultset: publicqobject {q_object q_property (attributes) Public: explicit it cresultset (qobject * parent = 0 ); cresultset (constcresultset &); // copy the constructor q_invokable void say (); q_invokable qstring getname () const {returnm_name;} q_invokable void setname (constqstring & name) {m_name = Name;} cresultset & operator = (constcresultset &); // overload value assignment operator PRIVATE: qstringm_name ;}; # endif/cresultset_h

 

To realize the introspection of C ++, we must first inherit the qobject class of QT from the public, and then use the q_object macro to notify the implementation of introspection. If you directly use the q_object macro without inheriting the qobject class, an error is returned. The q_property macro is used to identify the member variables that can be saved internally. It looks very strange to write in parentheses (you can see why you want to write this code below) to define the type of member variables, name and the setter and getter functions that read and write the member variable. The q_invokable macro is used to identify the member functions that can be saved. If the macro is not identified in the member variables or member functions,-1 is always returned when the indexofproperty and indexofmethod functions are called, that is, internal provinces cannot be used. Compared with the implementation of Java, the QT macro is more controllable and the control granularity is more detailed.

In addition, you need to pay attention to the issues when inheriting qobject. In the qobject class, the value assignment operator and the copy constructor are defined as private. That is to say, the class inherited from the qobject class cannot perform the value assignment operation and object copy. To solve this problem, we must re-implement the copy constructor and overload the value assignment operator.

The following code is the content of the CPP file: cresultset. cpp

 

#include"cresultset.h"
 #include<QDebug>   
CResultSet::CResultSet(QObject*parent):     QObject(parent) 
{ 
}   
// Copy the constructor
 CResultSet::CResultSet(constCResultSet&other)
{    
 *this=other; 
}   
voidCResultSet::say() 
{     
qDebug()<<this->m_name;
}   
// Overload the value assignment operator
CResultSet&CResultSet::operator=(constCResultSet&other) 
{    
 this->m_name=other.m_name;   
  return*this; 
}

The following code calls the meta-object feature: Main. cpp

#include<QtGui/QApplication> #include<QDebug> #include<QMetaObject> #include<QMetaProperty>   intmain(intargc,char*argv[]) {     QApplicationa(argc,argv);       CResultSetrs;     intpidx = (rs.metaObject())->indexOfProperty("m_name");     qDebug()<<pidx;       QMetaPropertyproperty=(rs.metaObject())->property(pidx);     property.write(&rs,QVariant("jacktan111"));     QMetaObject::invokeMethod(&rs,"say",Qt::DirectConnection);       intresult=a.exec();     returnresult; }

 

You can call the metaobject () function of an object to obtain the qmetaobject object of the object. The object contains all metadata, including the class name, member function, and member variable, signals and slots, similar to the class in Java. The indexofproperty function of the qmetaobject object can return the index value of the specified member variable name, and then call the qmetaobject: Property (INT) function using the index value to obtain the qmetaproperty object, this object is similar to the field class in Java and stores metadata about member variables. The Read and Write Functions in the qmetaproperty object are used to read and write member variables respectively. I believe everyone understands it! The previous q_property macro defined such a strange shape. The Read and Write Functions in the qmetaproperty object are implemented by using the function names specified by read and write.

You can use the static function invokemethod of the qmetaobject object to call the member functions of the specified object, provided that the called member functions must be modified by the q_invokable macro. There are two methods to call a member function: synchronous and asynchronous. The QT: directconnection parameter is used synchronously and the QT: queuedconnection parameter is used asynchronously. The functions of the above C ++ code are exactly the same as those of the Java version. Assign values to the member variables of an instantiated object through the introspection feature and call the specified member function. In contrast, Java's introspection is easier to understand and use, and at least there are no macro definitions that are confusing.

Finally, let's talk about the C ++ development framework of QT. It's powerful and self-explanatory, and time proves everything. In particular, its cross-platform capability is no less than a Java program that runs everywhere. Anyone who has done cross-platform development knows how difficult it is to implement cross-platform applications. By compiling source code, you can completely destroy your good expectations for cross-platform applications, so why does Java bother promoting its cross-platform capabilities. For developers, there is no need to worry about the platform on which the written code will run in the future. However, the cross-platform Java is based on the force of JVM, And the JVM itself is not cross-platform. Each platform has its own specific JVM implementation, but it is transparent to developers without the attention of developers. C ++ executes code at compilation cost, without just such as JVM.
In-time runtime system. So from this point of view, the cross-platform implementation of QT is more powerful than Java, but there is no free dinner in the world, in order to achieve cross-platform implementation, QT has passed all the burden to programmers, in order to achieve cross-platform, programmers need to think more carefully and use a large number of puzzling macro definitions.

The weakness of Java lies in its gui. Although browser-based applications are full, the GUI program does not exit the stage of history, in many cases, Gui programs are widely used in areas such as embedded systems and industrial applications with uniformity and high performance. This is why qtgui is active till now. In some enterprise applications, Java and C ++ can be perfectly combined. For example, Java is used to compile business logic components and give full play to its advantages in object-oriented modeling. C ++ qt gui can use a cross-language communication mechanism to interact with Java server components to achieve a high-performance User Interface experience. In other cases, we can use qt c ++'s high performance to write server-side business processing, and use Java to write the B/S interface to solve the unified deployment problem, fully integrates the advantages of the two development languages. Therefore, the best designers should not stick to the implementation platform in one language. They should make full use of the advantages of various platforms to create a perfect application system.

Qt draws on Java design concepts in many aspects, such as qt's GUI Component Model, QT's introspection, QT's layout manager, and QT's MVC model. The shadows of Java design are everywhere. So if you are a Java developer, you will surely feel familiar when you encounter QT.

From: http://www.xue5.com/Developer/Software/628217.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.