0

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

}

4

2 回答 2

1

使您的方法成为最终方法,并在其中添加某种配置。

public final void doSomething() {
   if (switchedOn) return;
   // rest if the code. 
}

通过在 final 中进行设置,您可以使没有人覆盖扩展它的类中的方法。

通过在函数中返回,您可以确保当某些条件存在时,不会发生其他任何事情

于 2019-12-21T16:04:36.263 回答
0

你说你可以用 if else 子句来做到这一点。但是如果可以调用该方法,他们是否也可以更改标志。

你可以用一些access restrictions方法unaccessible来制作。

您还可以将该方法放在 a 中private inner class,并通过该类的实例化使其可用。完成该方法后,请摆脱该实例。如果它是私有的,那么没有人应该能够调用它。但是对于私有方法也是如此。

public class MainClass {
   String msg = "Hello, World!";

   public static void main(String[] args) {
      MainClass a = new MainClass();
      a.start();
   }
   public void start() {
      MyClass pvtClass = new MyClass();
      System.out.println(pvtClass.getMsg());
   }

   private class MyClass {

      private String getMsg() {
         return msg;
      }
   }
}

但据我所知,您无法卸载方法。

于 2019-12-21T16:08:56.143 回答