Reputation: 77
I have a scenario where I call a particular method at multiple parts in my code.Now I need this method to be not implemented or the lines within this code not be executed for a particular condition ( like example a ON/OFF switch). I can add a if...else , everywhere where I am calling that method. but is there any other way to do it in java . maybe at method level?
As I mentioned don't want to add my if ..else everywhere where I call the method. Adding example below:
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();
}
}
Upvotes: 0
Views: 56
Reputation: 40024
You said you can do it with an if else clause. But if the could call the method, couldn't they also change the flag.
You could use access restrictions
to make the method unaccessible
to some.
You could also put the method in a private inner class
and make it available via an instantiation of that class. When you are done with the method, get rid of the instance. If it is private, no one should be able to invoke it. But the same is true for a private method too.
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;
}
}
}
But as far as I know, you can't unload a method.
Upvotes: 0
Reputation: 26352
Make your method final and add some kind if configuration in it.
public final void doSomething() {
if (switchedOn) return;
// rest if the code.
}
By making in final you make that none override the method from the classes that extend it.
By returning in the function you make sure that when some condition exists, nothing else happens
Upvotes: 1