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?
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?
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
You can initialize an object by wrapping code with extra curly braces.
Test myObject;
myObject=new Test()
{
{
myMethod1();
myMethod2();
myMethod3();
}
};
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.
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();
...