jeudi 22 janvier 2015

Implementing reflection mechanism in C++

So I'm trying to create a mechanism that would be similar to the Java reflection mechanism, making the language support 3 levels of abstraction, e.g: Creating 4 new classes: MetaClass, Object, Field, Method.


MetaClass is similar to "Class" class in Java, etc.


To give an example of I would expect it to work, take a look at this code:



class A{}
class B{}
MetaClass<A> A_class(NULL, "A") // bulding new class, super = NULL
MetaClass<B> B_class(&A_class, "B") // B_class inherits from A_class
A_class.addInstanceField("x", PUBLIC);
Object* a = A_class.newInstance();
cout << a->getFieldValue("x"); // prints 0, because default value of a field is 0 (and let's assume it will always be an int)
a->setFieldValue("x", 5);
cout << a->getFieldValue("x"); // prints 5.


I hope you get the idea. My problem is the design. this is how I defined MetaClass's fields:



std::list<Field>* fields;
std::list<Method>* methods;
MetaClass<T&>* superClass;
std::string className;
static bool instanceFlag = false;


and I'm having hard time figuring out how to implement the function that adds a field/method to the class, and how to know the difference between adding a static member or an instance member (I know what's the difference i just don't know how to design it well in my case)


e.g these functions are my problems:



void addInstanceMethod(std::string name, Modifier mod, Func func);

void addStaticMethod(std::string name, Modifier mod, Func func);

void addInstanceField(std::string name, Modifier mod);

void addStaticField(std::string name, Modifier mod);


plus, if you can help me with getting to unferstand this one as well it would be awsome:



virtual void invokeStaticMethod(std::string name);


hope my problem is clear.






Aucun commentaire:

Enregistrer un commentaire