我想创建一个能够按名称动态调用其他类中的方法的类。理想情况下,它会接受类和方法名称以及参数集合。 dictClass在静态方法上运行良好,但似乎不适用于实例方法。
有没有办法让以下代码适用于非静态方法?
[SysEntryPointAttribute]
public str methodExecute(str className, str methodName, str params)
{
DictClass dictClass;
anytype retVal;
str connMessage;
ExecutePermission perm;
perm = new ExecutePermission();
// Grants permission to execute the DictClass.callStatic method.
// DictClass.callStatic runs under code access security.
perm.assert();
dictClass = new DictClass(className2Id(className));
if (dictClass != null)
{
retVal = dictClass.callStatic(methodName);
connMessage = strfmt("Return value is %1", retVal);
}
// Closes the code access permission scope.
CodeAccessPermission::revertAssert();
return connMessage;
}
答案 0 :(得分:1)
static void Job_Example_DictClass_CallObject(Args _args)
{
DictClass dictClass;
anytype retVal;
str resultOutput;
ExecutePermission perm;
perm = new ExecutePermission();
// Grants permission to execute the DictClass.callObject method.
// DictClass.callObject runs under code access security.
perm.assert();
dictClass = new DictClass(classidget(infolog));
if (dictClass != null)
{
retVal = dictClass.callObject("toString", infolog);
resultOutput = strfmt("Return value is %1", retVal);
print resultOutput;
pause;
}
// Closes the code access permission scope.
CodeAccessPermission::revertAssert();
}
同时尝试查看DictClass.MakeObject:
答案 1 :(得分:1)
以下代码应该可以解决问题。我下面的代码可以使用类名,也可以接受已经实例化的所需类型的对象。
最大的问题是处理传递参数。由于存在可变数字,因此我使用switch语句将正确数量的参数传递给方法。这看起来不太优雅,但我不确定还有另一种方法可以实现这一点。
public static anytype callMethod(str _className, str _methodName, container _parameters, Object _object = null)
{
DictClass dictClass;
anytype returnValue;
Object object;
ExecutePermission permission;
// Grants permission to execute the DictClass.callObject method.
// DictClass.callObject runs under code access security.
permission = new ExecutePermission();
permission.assert();
if (_object != null)
{
dictClass = new DictClass(classidget(_object));
object = _object;
}
else
{
dictClass = new DictClass(className2Id(_className));
object = dictClass.makeObject();
}
if (dictClass != null)
{
switch (conLen(_parameters))
{
case 0:
returnValue = dictClass.callObject(_methodName, object);
break;
case 1:
returnValue = dictClass.callObject(_methodName, object, conPeek(_parameters, 1));
break;
case 2:
returnValue = dictClass.callObject(_methodName, object, conPeek(_parameters, 1), conPeek(_parameters, 2));
break;
//... Continue this pattern for the number of parameters you need to support.
}
}
// Closes the code access permission scope.
CodeAccessPermission::revertAssert();
return returnValue;
}