0

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

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)

简而言之,我正在寻找一种方法来接受从 a 返回的东西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(带有大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) {}

感谢您的帮助!

4

1 回答 1

0

The most direct way to solve this problem would be to have the void methods return Void instead, which you've already called out. The void type will never be accepted as a value type in Java, so the style you're using won't work for void.

Another approach would be to allow users to provide a Runnable, which is then run on their behalf, and then have them call the void method in the Runnable.

于 2013-07-11T19:48:57.097 回答