首先看一下实现后的C++函数反射如何使用:
1.首先定义一个类:
DECLARE_CLASS(testReflect_1) {
public:
int sayhi(int v) {
printf("sayhi!!!!!. \n");
return v + 1;
}
String sayhello(int v,int j) {
return String::New(v + j)->append(" is ok!!!");
}
DECLARE_REFLECT_METHOD(testReflect_1,sayhi,sayhello)
};
和之前申明成员变量反射类似的宏DECLARE_REFLECT_METHOD,testReflect_1是类目,后面可以添加需要反射的函数。应该算是比较简单的申明了。
然后我们看一下怎么使用:
Object t = (Object)testReflect_1::New();
auto method = t->getMethodField("sayhi");
auto result = method->execute(123);
printf("result is %d \n",result->get<int>());
auto method2 = t->getMethodField("sayhello");
auto result2 = method2->execute(1,2);
printf("result2 is %s \n",result2->get<String>()->toChars());
getMethodField函数根据函数名字来找到需要反射的函数
execute函数对应的就是执行被反射的函数。执行结果存放在如下结构体:
DECLARE_CLASS(MethodResult) {
public:
template<typename T>
_MethodResult(T v) {
result = v;
}
template<typename T>
T get() {
return std::any_cast<T>(result);
}
private:
std::any result;
};
模板中指定返回数据类型,get方法会强转。用起来还是比较方便的。
Obotcha链接:
https://github.com/wangsun1983/Obotcha/tree/master
反射实现:
https://github.com/wangsun1983/Obotcha/blob/master/lang/include/ReflectMethod.hpp