从方法接受返回类型void?

时间:2013-07-11 19:47:15

标签: java methods types parameters void

我正在开发一个测试类,它允许用户进行任意方法调用。然后我的班级会触发它们。

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()返回的 thing 到方法参数中。

(或变成一个变量 - 差别不大)

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(大V),这不是void(小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) {}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

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

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

相关问题