java - 限制或阻止方法的实现

标签 java methods readonly-attribute

我有一个场景,我在代码的多个部分调用特定方法。现在我需要不实现此方法,或者在特定条件下不执行此代码中的行(例如 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/

相关文章:

javascript - 只读属性和 ngOnInit

jquery - 如何禁用只读字段上的 jquery 验证?

java.sql.SQLException : No suitable driver found for jdbc:mysql://localhost/WORLD

java - 如何使用 MVC 在 CardLayout 中的 JPanel 之间切换?

java - 特许经营类的compareTo方法

java - Java 中的 repaint() 方法是否需要计时器或操作?

java - 如何从对象中调用变量?

java - TextView定时器秒数字跳跃

ruby-on-rails - 在 ruby​​ (NoMethodError) 模块中定义一个方法