【问题标题】:Accepting return type void from a method?接受方法的返回类型 void?
【发布时间】: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的课程。但它只接受nullVoid(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


【解决方案1】:

解决此问题的最直接方法是让void 方法返回Void,您已经调用了它。 void 类型在 Java 中永远不会被接受为值类型,因此您使用的样式不适用于 void

另一种方法是允许用户提供Runnable,然后代表他们运行,然后让他们在Runnable 中调用void 方法。

【讨论】:

  • 感谢您的回答。我可能需要查看Runnable,它可能会解决我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-31
  • 2014-04-23
相关资源
最近更新 更多