我有一个类如下,
public class Class1 {
public void method1(String data){
}
public void method2(String data){
}
}
我正在使用它,
public class Class2{
public void doSomething(){
Class1 class1 = new Class1();
class1.method1("123");
// doSomething will find a value as result
class1.method2(result);
}
}
调用method1();
时必须调用method2();
。
如果只有 method1();
正在调用,我需要显示编译时错误。
我们怎样才能达到同样的效果。
就像 Class2
我有很多类,每个类中的 doSomething
都是不同的。
最佳答案
我会说你想要实现的是“不能完成”和“不应该完成”的混合体,只要你希望编译器完成它。
问问自己:以下代码片段是否有效?
class1.method1();
class1.method1();
class1.method2();
或
public void doSomething(){
Class1 class1 = new Class1();
class1.method1();
callIt(class1);
}
void callIt(Class1 class1) {
class1.method2();
}
或
class1.method1();
if (true) return;
class1.method2();
我怀疑您能否为这三个片段(以及我能想出的更多)提出一个好的和合理的论据。归结为:什么代码结构满足您“必须调用 method2”的要求?
基本上这个要求根本无法执行!
唯一有效的方法可能是改变 method1
的工作方式:让它接受一个 Runnable
作为调用者必须传递的参数,从而使调用者能够在 method1
的常规处理完成后进行操作。然后从 method1
中调用 method2
:
public void method1(Runnable postRunAction) {
// regular computation
postRunAction.run();
method2();
}
如果您想使用方法的返回值,让示例更复杂一些:
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 */
});
}
}
关于java - Java 中的方法限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41919245/