Java equivalent of VB with ... End With

Possible duplicate:
WITH statement in Java

In Visual Basic, I could do this:

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

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

+4
source share
4 answers

There is no exact equivalent to the with statement. In the context of VB, it is syntactic sugar. You can create a temporary link to everything you want to do with the "c".

Also syntax

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

which may be equivalent

 ... m = myObject; m.myMethod1(); ... 
+1
source

Not really. If you need to perform a bunch of operations on an object, it may make sense to encapsulate them in a function and place them in this class of objects.

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

You can also look at this question that was posted earlier: WITH statement in Java

+2
source

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 function in some languages ​​with similar syntax has one additional advantage, besides saving, in order to type expression more: it automatically closed the object at the end of the block, even if some exception occurred in the block.

There was some discussion about adding this word to Java, and it looks like it was in JDK 7. The syntax would be a bit, however, as an extension of the try statement. Then you can write

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

... and Reader (and all threads wrapped by it) will be automatically closed after reading (or exception).

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

You still have to call the object a name (variable) inside the block.

+1
source

You can initialize the object by wrapping the code with additional curly braces.

 Test myObject; myObject=new Test() { { myMethod1(); myMethod2(); myMethod3(); } }; 
+1
source

Source: https://habr.com/ru/post/1339438/


All Articles