4

Possible Duplicate:
WITH statement in Java

In Visual Basic, I could do this:

With myObject
    .myMethod1()
    .myMethod2()
    .myMethod3()
End With

I'm wondering if there is an equivalent in Java for this?

Community
  • 1
  • 1

4 Answers4

2

Not really. If you need to do a bunch of operations on an object it might make more sense to encapsulate those in a function and put it in that object's class.

public void doStuff() {
    myMethod1();
    myMethod2();
    myMethod3();
}

...

myObject.doStuff();

You might also want to look at this question that was posted previously: WITH statement in Java

Community
  • 1
  • 1
takteek
  • 7,020
  • 2
  • 39
  • 70
  • Sorry for double posting a question. :) I usually do encapsulate them in a method, but I was looking to see if setting the "namespace" to an object was possible or not. Thanks! –  Feb 12 '11 at 02:26
2

You can initialize an object by wrapping code with extra curly braces.

Test myObject;

myObject=new Test()
{
  {
    myMethod1();
    myMethod2();
    myMethod3();
   }
};
Community
  • 1
  • 1
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
1

Not really, but you can do something like

{
  MyClass m = reallyLongExpressionReturningAnObject();
  m.myMethod1();
  m.myMethod2();
  m.myMethod3();
}

I don't know Visual Basic, but a feature in some languages with a similar syntax has one additional advantage apart from saving to type the expression more times: It would automatically close the object at the end of the block, even when some exception occurred in the block.

There was some discussion about adding this to Java, and it looks like it is accepted to be in JDK 7. The syntax would be a bit different, though, as an extension of the try statement. You can then write

try (BufferedReader in = new BufferedReader(new FileReader(...))) {
    String line;
    while((line = in.readLine()) != null) {
       list.add(line);
    }
}

... and the Reader (and all the streams wrapped by it) would be closed automatically after reading (or on an exception).

This would work for all objects implementing the (new) java.lang.AutoClosable interface. If an exception is thrown in the block itself, and during cleanup another exception occurs, this other exception is suppressed and appended to the original exception with addSuppressed(...).

You would still have to call the object by (variable) name inside the block, though.

0x6C38
  • 6,796
  • 4
  • 35
  • 47
Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
1

There is no exact equivalent to the with statement. In the VB context, it is syntactic sugar. you can create a temporary reference to whatever you want to do the "with" with.

Also, the syntax is

With myObject
    .myMethod1()
    .myMethod2()
    .myMethod3()
End With

which could be equivalent to

... m = myObject; 
m.myMethod1(); 
...
Foo Bah
  • 25,660
  • 5
  • 55
  • 79