Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy with block in Java

Tags:

java

groovy

In groovy, there is a with block, which can be used to call methods on a object like this:

obj.with
{
   method1()
   method2()
}

where method1,method2 are methods for object obj.

Is the same is possible in Java 7? I mean can we make some way to do this in java?

Thanks in advance.

like image 291
batman Avatar asked May 20 '26 20:05

batman


1 Answers

There isn't anything similar to with in Java 7. The closest you can do is use an Initialization block while instantiating an anonymous class:

       new Test() {
            {
                method1();
                method2();
            }
        };

which might not suit every case, as you can only use it for initialization.

Where Test is:

class Test{
    public void method1() {
        System.out.println(1);
    }

    public void method2() {
        System.out.println(2);
    }
}
like image 53
Shail016 Avatar answered May 22 '26 11:05

Shail016



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!