【发布时间】:2013-07-11 19:47:14
【问题描述】:
我正在开发一个测试类,它允许用户进行任意方法调用。然后我的班级会触发它们。
static class UserClass {
static String method_01() { return ""; }
static void method_02() {}
}
class MyTestUtil {
void test() {
// HowTo:
// performTest( <Please put your method calls here> );
performTest( UserClass.method_01() ); // OK
performTest( UserClass.method_02() ); // compile error
}
void performTest(Object o) {}
// This is only a simplified version of the thing.
// It is okay that the UserClass.method_calls() happens at the parameter.
// This captures only the return value (if any).
}
第二个performTest() 出现以下编译错误。
Main.MyTestUtil 类型中的方法 performTest(Object) 不适用于参数 (void)
简而言之,我正在寻找一种方法来接受从void function() 返回的事物,并将其转换为方法参数。
(或者变成一个变量——差别不大)
static void function() {}
public static void main(String[] args) {
this_function_accepts ( function() );
// The method this_function_accepts(Void) in the type Main is not applicable for the arguments (void)
Void this_var_accepts = function();
// Type mismatch: cannot convert from void to Void
}
我做了一些研究。我意识到了java.lang.Void的课程。但它只接受null或Void(with big V)类型,不是void(small v),对用户的方法不正常。
// adding these overloading methods doesn't help
void this_function_accepts() {}
void this_function_accepts(Void v) {}
void this_function_accepts(Void... v) {}
void this_function_accepts(Object v) {}
void this_function_accepts(Object... v) {}
感谢您的帮助!
【问题讨论】:
-
我不知道你为什么希望这能工作。
void方法不返回任何内容。你为什么想做这个?performTest做什么没有结果? -
即使对于非 void 方法,您的解决方案也不起作用。您的方法的问题在于,您应该测试的方法的调用将在调用
performTest方法之前发生。本质上,您的performTest将获得被测试方法的返回值 - 它无法调用该方法或为其提供任何参数。 -
在您的示例中, performTest() 没有被传递一个可以在设置和拆卸后运行的方法——它被调用 在该方法已经运行之后,使用方法调用的结果。
-
那为什么还有
performTest方法呢?你试图做的事情没有意义。如果你只想调用一个方法,那么就调用那个方法。 -
方法的实际参数是值。 void 关键字表示方法没有返回值。您不能将 void 方法的返回值作为值传递,因为它不存在。
标签: java methods types parameters void