我有一个场景,我在代码的多个部分调用特定方法。现在我需要不实现此方法,或者在特定条件下不执行此代码中的行(例如 ON/OFF 开关) )。我可以在调用该方法的任何地方添加 if...else 。但有没有其他方法可以在 java 中做到这一点。也许在方法级别?
正如我提到的,不想在调用该方法的任何地方添加 if ..else 。 添加以下示例:
public class Example {
static boolean readOnly = true;
public static void getWorkDone() {
System.out.println("I am working to get it done!!");
}
public static void main(String[] args) {
if (readOnly == true)
Example.getWorkDone();
}
public void anotherMethod1() {
if (readOnly == false)
Example.getWorkDone();
}
public void anotherMethod2() {
if (readOnly == true)
Example.getWorkDone();
}
}
最佳答案
使您的方法最终并在其中添加某种 if 配置。
public final void doSomething() {
if (switchedOn) return;
// rest if the code.
}
通过将其设置为final,您可以确保没有人会覆盖扩展该方法的类中的方法。
通过返回函数,您可以确保当某些条件存在时,不会发生其他情况
关于java - 限制或阻止方法的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59437650/