Java中的方法限制

Rak*_* KR 2 java methods

我有一个课程如下,

public class Class1 {
    public void method1(String data){         
    }
    public void method2(String data){
    }
}
Run Code Online (Sandbox Code Playgroud)

而我正在使用它,

public class Class2{
    public void doSomething(){
        Class1 class1 = new Class1();
        class1.method1("123");
        // doSomething will find a value as result
        class1.method2(result);
    }
}
Run Code Online (Sandbox Code Playgroud)

呼叫method2();时必须method1();呼叫.
如果只是method1();调用我需要显示编译时错误.
我们怎样才能实现同样的目标.
就像Class2我有很多课程一样,每个课程都有doSomething所不同.

luk*_*302 5

我想说你想要实现的是"无法完成"和"不应该完成"的混合,只要你想让编译器去做.

问问自己:以下代码片段是否有效?

class1.method1();
class1.method1();
class1.method2();
Run Code Online (Sandbox Code Playgroud)

要么

public void doSomething(){
    Class1 class1 = new Class1();
    class1.method1();
    callIt(class1);
}

void callIt(Class1 class1) {
    class1.method2();
}
Run Code Online (Sandbox Code Playgroud)

要么

class1.method1();
if (true) return;
class1.method2();    
Run Code Online (Sandbox Code Playgroud)

我怀疑你能为这三个片段提出一个好的和合理的论点(还有更多我想出的).归结为:什么构造的代码满足您的要求"必须调用method2"?

基本上这个要求根本无法执行!


唯一有效的方法可能是改变method1工作方式:让它接受Runnable调用者必须传入的as参数,这使得调用者能够在method1完成常规处理之后进行操作.然后method2从内部打电话method1:

public void method1(Runnable postRunAction) {
    // regular computation
    postRunAction.run();
    method2();
}
Run Code Online (Sandbox Code Playgroud)

如果要使用方法的返回值,要使示例更复杂一些:

public class Class1 {
    public SomeReturnType2 method1(Function<SomeReturnType1, SomeParameterType1> yourDoSomething) {         
        SomeReturnType1 something = /* your computation of method1 */
        SomeParameterType1 param = yourDoSomething.apply(something);
        return method2(param);
    }

    private SomeReturnType2 method2(SomeParameterType1 param1){
        // do some calculation of method2
    }
}

public class Class2 {
    public void doSomething(){
        Class1 class1 = new Class1();
        class1.method1((theReturnValueOfMethod1Computation) -> {
            /* do what do you want to do with the return value + return what do you want to pass to method2 */
        });
    }
}
Run Code Online (Sandbox Code Playgroud)