batman
batman

Reputation: 4928

Groovy with block in Java

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.

Upvotes: 3

Views: 1382

Answers (1)

Shailesh Aswal
Shailesh Aswal

Reputation: 6802

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);
    }
}

Upvotes: 3

Related Questions