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!


Solution 1:

No. The best you can do, when the expression is overly long, is to assign it to a local variable with a short name, and use {...} to create a scope:

{
   TypeOfFoo it = foo; // foo could be any lengthy expression
   it.bar();
   it.reset(true);
   myvar = it.getName();
}

Solution 2:

Perhaps the closest way of doing that in Java is the double brace idiom, during construction.

Foo foo = new Foo() {{
    bar();
    reset(true);
    myVar = getName(); // Note though outer local variables must be final.
}};

Alternatively, methods that return this can be chained:

myName =
    foo
        .bar()
        .reset(true)
        .getName();

where bar and reset methods return this.

However, wanting to do this tends to indicate that the object does not have rich enough behaviour. Try refactoring into the called class. Perhaps there is more than one class trying to get out.

Solution 3:

You can get quite close using Java 8 lambdas, with a drawback of not being able to modify local variables.

Declare this method:

static <T> void with(T obj, Consumer<T> c) {
    c.accept(obj);
}

So you can use:

Window fooBarWindow = new Window(null);

String mcHammer = "Can't Touch This";

with(fooBarWindow, w -> {
     w.setAlwaysOnTop(true);
     w.setBackground(Color.yellow);
     w.setLocation(300, 300);

     w.setTitle(mcHammer); // can read local variables
     //mcHammer = "Stop!"; // won't compile - can't modify local variables
});

This is also possible using an anonymous class, but not as clean.