WITH statement in Java

Viewed 29535

In VB.NET there is the WITH command that lets you omit an object name and only access the methods and properties needed. For example:

With foo
   .bar()
   .reset(true)
   myVar = .getName()
End With

Is there any such syntax within Java?

Thanks!

8 Answers

If you have hands on the implementation of Foo, you can use the fluent API concept.

Lets say you have that:

public class Foo {
    private String a;
    private String b;
    public void setA(String a) { this.a = a; }
    public void setB(String b) { this.b = b; }
    public String getName() { return this.a + " " + this.b; }
}

Then you could modify it to obtain this:

public class Foo {
    private String a;
    private String b;
    public Foo setA(String a) { this.a = a; return this; }
    public Foo setB(String b) { this.b = b; return this; }
    public String getName() { return this.a + " " + this.b; }
}

And your calling code could look like:

String name = new Foo().setA("foo")
                       .setB("bar")
                       .getName();

Enjoy!

Related