views:

996

answers:

6

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!

+1  A: 

Nope. Java has a policy of avoiding anything that might reduce verbosity.

Well, after writing this it just occurred to me that the closest thing might be static imports, e.g.

package a.b.c.d;
Class Foo {
   public static void bar(){...
}

and now you can do

 package d.e.f;
 import static a.b.c.d.Foo;

 bar();
Steve B.
+8  A: 

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();
}
Pavel Minaev
My understanding of VB isn't great, but I don't think it is doing that.
Tom Hawtin - tackline
(The equivalent Java would be `foo.bar(); foo.reset(true); String myVar = foo.getName();`.)
Tom Hawtin - tackline
It would, but it doesn't make much point to do this at all when you already have a variable such as `foo`, which is why I changed the example to involve a more complicated expression. In VB also, `With` is more often used with lengthy expressions. Also, there's no need to declare `myVar` - presumably it's already declared in outer scope. `True` needs correcting though, thanks for pointing that out.
Pavel Minaev
+2  A: 

The closest thing to this is static imports that will allow you to call static methods without explicitly specifying the class on which the method exists.

daveb
+2  A: 

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 ahve rich enough behaviour. Try refactoring into the called class. Perhaps there is more than one class trying to get out.

Tom Hawtin - tackline
+2  A: 

Some objects allow you to "chain" method invocations, which approaches the syntax you like. For example, often a Builder class will return itself from methods so you can do something like this:

MyObject b = new MyBuilder().setFoo(5).setBar(6).setBaz("garply!").build();

Each "set" method returns "this" so you can chain the next invocation.

Steven Schlansker
A: 

Tom Hawtin above is correct, double brace idiom is the closest. But I cant vote for it because I'm new here...

Dan