Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Methods in Sequence

Tags:

java

methods

I have 5 different methods like this

public void met1(){}
public void met2(){}
public void met3(){}
public void met4(){}
public void met5(){}

I want to call this method from 1 to 5 is there any convinient way to do this.

I don't want to call one by one or I don't want to put method call inside other method.

How Can I do this??

like image 246
akash Avatar asked Aug 31 '26 13:08

akash


2 Answers

I believe you could do it with reflection with something like:

YourClass classInstance = new YourClass();

for (int i = 1; i < 6; i++) {
    Method yourMethod = YourClass.class.getMethod("met" + i);

    method.invoke(instance);
} 

Haven't tested it out, so no guarantees.

like image 133
Igor Avatar answered Sep 02 '26 03:09

Igor


You can use the Execute Around Method pattern.

public class Resource {
    private Resource(){}
    public void opc1(){
        System.out.println("Opc1");
        // use can use cascade pattern( return this)
    }

    public void opc2(){
        System.out.println("Opc2");
        // use can use cascade pattern( return this)
    }

    public void opc3(){
        System.out.println("Opc3");
        // use can use cascade pattern( return this)
    }
    public void closeResource(){
        System.out.println("Release resource");
    }
    public static void use(Consumer<Resource> consumer){
        Resource resource =new Resource();
        consumer.accept(resource);
        resource.closeResource(); // force to execute closeResource method
    }

    public static void main(String[] args) {
        Resource.use(resource -> {
            resource.opc1();
            resource.opc3();
            resource.opc2();
        });
    }
}

More info at https://agiledeveloper.com/

like image 25
srr7 Avatar answered Sep 02 '26 03:09

srr7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!