I have several methods in a class that require a boolean to be set to true in order to execute correctly.
I could write the if
statement in each method, but it is not convenient if I or someone else wants to ad another method. I or he could forget about the check.
Is there a way in java to execute a method before each other methods (exactly like JUnit does with @BeforeEach
) in a class ?
Edit: Lots of very interesting techniques/answers/concepts proposed. I'll be in touch when I've understood them. Thanks.
Main() is a method that always execute first when we run our program. when we have multiple methods inside the class we can call them or execute them by simply write method name with () inside Main() method.
This Java program is used to call method in same class. Example: public class CallingMethodsInSameClass { // Method definition performing a Call to another Method public static void main(String[] args) { Method1(); // Method being called.
Abstract—As the order of methods in a Java class has no effect on its semantics, an engineer can choose any order she prefers.
The main() method is the entry point of each and every Java program. The main() method is required because the compiler starts executing a program from this entry point. The JVM needs to instantiate the class if the main() method is allowed to be non-static.
Lets make a method turnBooleanTrue()
where effectively the boolean
is set to true in order for the method to be execute correctly.
Then, you can write up your very own InvocationHandler that would intercept calls to your objects, and then reflectively (using reflection API) invoke first the turnBooleanTrue()
method followed by the method to which the call was made.
Will look something like this
public class MyClassInvocationHandler implements InvocationHandler {
// initiate an instance of the class
MyClass myClass = new MyClassImpl();
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// look up turnBooleanTrue() method
Method turnBooleanTrue = myClass.getClass().getMethod("turnBooleanTrue");
// invoke the method
turnBooleanTrue.invoke(...); // toggle the boolean
// invoke the method to which the call was made
// pass in instance of class
Object returnObj = method.invoke(myClass, args);
return returnObj;
}
EDIT
Added some lines to have an object of MyClass
initialized. You need something to invoke the method on and maintain the state. Changed util
to myClass
in the code example above.
Considering my use case, it was a bit overkill to use AOP or other concepts. So I basically did a check in each functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With