全部,
虽然这与另一篇文章类似,但该文章(没有说明如何在不实例化对象的情况下执行此操作(如果可以的话)。此外,我尝试了多种主题变体,但均未成功:
class[method](arg)
class[method].call(arg)
method.apply(class, arg)
我是 Flex 的新手,但在 C# 和 Java 中都使用过反射。顺便说一句,我试图在 Flex 中工作的代码在这两种语言中都有镜像,并且可以按预期工作。
任何帮助表示赞赏,谢谢,托德
无效的弹性代码:
private function ipMethodTester( ipMethodName:String,
shouldPass:Array, shouldFail:Array):void
{
var message:String;
var entry:String;
for each(entry in shouldPass)
{
message = ipMethodName + ": " + entry + " should pass";
try
{
Assert.assertTrue(message,
FieldValidator[ipMethodName](entry));
}
catch(e:Error)
{
Assert.fail(e.message + " " + message);
}
}
for each(entry in shouldFail)
{
message = ipMethodName + ": " + entry + " should fail";
try
{
Assert.assertFalse(message,
FieldValidator[ipMethodName](entry));
}
catch(e:Error)
{
Assert.fail(e.message + " " + message);
}
}
}
Java 代码:
private void ipMethodTester(final String ipMethodName,
final String[] shouldPass, final String[] shouldFail)
{
Method method;
try
{
method = InetUtil.class.getDeclaredMethod(ipMethodName, String.class);
method.setAccessible(true);
for(String entry : shouldPass)
{
Object[] invokeArgs = { entry };
boolean passed = (Boolean)method.invoke(null, invokeArgs);
assertTrue(ipMethodName + ": " + entry + " should pass", passed);
}
for(String entry : shouldFail)
{
Object[] invokeArgs = { entry };
boolean passed = (Boolean)method.invoke(null, invokeArgs);
assertFalse(ipMethodName + ": " + entry + " should fail", passed);
}
}
catch (final Exception e)
{
fail(e.getClass().toString());
}
}
C#代码:
private void ipMethodTester(string ipMethodName, string[] shouldPass, string[] shouldFail)
{
Type type = typeof (ValidateUtil);
BindingFlags bindingFlags = BindingFlags.InvokeMethod
| BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
MethodInfo method = type.GetMethod(ipMethodName, bindingFlags);
foreach(string entry in shouldPass)
{
object[] invokeArgs = { entry };
bool passed = (bool)method.Invoke(null, invokeArgs);
Assert.IsTrue(passed, ipMethodName + ": " + entry + " should pass");
}
foreach(string entry in shouldFail)
{
object[] invokeArgs = { entry };
bool passed = (bool)method.Invoke(null, invokeArgs);
Assert.IsFalse(passed, ipMethodName + ": " + entry + " should fail");
}
}