WITH statement in Java

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?


-------------Problems Reply------------

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
myvar = it.getName();

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

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

Alternatively, methods that return this can be chained:

myName =

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.

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.

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) {

So you can use:

Window fooBarWindow = new Window(null);

String mcHammer = "Can't Touch This";

with(fooBarWindow, w -> {
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.

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.

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;
public class Foo {
public static void bar() {

and now you can do

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


As already said, you cannot really write the code as this in Java.

Just as a comment, if you are affraid of many copy/paste in the case you need to change the variable name, Eclipse allows you to rename all the references of the variable automatically:

Using ALT+SHIFT+R on the "foo" variable name, you can rename all at once to "myFoo" for instance:

Foo myFoo = new Foo();

Category:java Views:0 Time:2009-09-29

Related post

  • Accessing post variables using Java Servlets 2008-08-07

    All I really want is the equivalent of PHP's $_POST[], and after searching the web for an hour, I'm still nowhere closer. --------------Solutions------------- Your HttpServletRequest object has a getParameter(String paramName) method that can be used

  • Java Time Zone is messed up 2008-08-08

    I am running a Tomcat application, and I need to display some time values. Unfortunately, the time is coming up an hour off. I looked into it and discovered that my default TimeZone is being set to: sun.util.calendar.ZoneInfo[id="GMT-08:00", offset=-

  • How should I load files into my Java application? 2008-08-09

    How should I load files into my Java application? --------------Solutions------------- The short answer Use one of these two methods: Class.getResource(String) Class.getResourceAsStream(String) For example: InputStream inputStream = YourClass.class.g

  • Java + SQL Server - a viable solution? 2008-08-09

    I'm going to start a new project - rewriting an existing system (PHP + SQL Server) from scratch because of some very serious limitations by design. We have some quite good knowledge of SQL Server (currently we're using SQL Server 2000 in existing sys

  • Class file name must end with .class exception in Java Search 2008-08-09

    I was hoping someone could help me out with a problem I'm having using the java search function in Eclipse on a particular project. When using the java search on one particular project, I get an error message saying Class file name must end with .cla

  • How can I identify in which Java Applet context I'm running without passing an ID? 2008-08-10

    I'm part of a team that develops a pretty big Swing Java Applet. Most of our code is legacy and there are tons of singleton references. We've bunched all of them to a single "application context" singleton. What we now need is to create some way to s

  • Any good java source code analyzing and modifying libraries? 2008-08-10

    I'm working on an app that converts source code from using one framework to another. I really wanted to make the agonizing monotonous job automatic. After looking a lot for something that could help me treat source code in an object-oriented way and

  • Use of java.math.MathContext 2008-08-11

    Recently I tried understanding the use of java.math.MathContext but failed to understand properly. Is it used for rounding in java.math.BigDecimal, if yes why does not it round the decimal digits but even mentissa part. From API docs, I came to know

  • How should I structure a Java application, in other words: where do I put my classes? 2008-08-11

    First of all, I know how to build a Java application. But I have always been puzzled about where to put my classes. There are proponents for organizing the packages in a strictly domain oriented fashion, others separate by tier. I myself have always

  • Java code for WGS84 to Google map position and back 2008-08-11

    Searching for some sample code for converting a point in WGS84 coordinate system to a map position in Google Maps (pixel position), also supporting zoom levels. If the codes is well commented, then it can also be in some other language. You can also

  • Packaging Java apps for the Windows/Linux desktop 2008-08-11

    I am writing an application in Java for the desktop using the Eclipse SWT library for GUI rendering. I think SWT helps Java get over the biggest hurdle for acceptance on the desktop: namely providing a Java application with a consistent, responsive i

  • What's your "best practice" for the first Java EE Spring project? 2008-08-12

    I'm currently trying to get into the Java EE development with the Spring framework. As I'm new to Spring, it is hard to imaging how a good running project should start off. Do you have any best practices, tipps or major DO NOTs for a starter? How did

  • How do I implement a Linked List in Java? 2008-08-13

    What's the best way to make a linked list in Java? --------------Solutions------------- The obvious solution to developers familiar to Java is to use the LinkedList class already provided in java.util. Say, however, you wanted to make your own implem

  • What is the best way to work around the fact that ALL Java bytes are signed? 2008-08-14

    In Java, there is no such thing as an unsigned byte. Working with some low level code, occasionally you need to work with bytes that have unsigned values greater than 128, which causes Java to interpret them as a negative number due to the MSB being

  • Getting Java and TWAIN to play together nicely 2008-08-14

    I'm working on building an app to scan directly from TWAIN scanner to a Java applet. I'm already aware of Morena and JTwain, but they cost money. I need free. I could re-invent the wheel with JNI, but it seems like someone has probably already done t

  • How can I determine the IP of my router/gateway in Java? 2008-08-15

    How can I determine the IP of my router/gateway in Java? I can get my IP easily enough. I can get my internet IP using a service on a website. But how can I determine my gateway's IP? This is somewhat easy in .NET if you know your way around. But how

  • Do you obfuscate your commercial Java code? 2008-08-15

    I wonder if anyone uses commercial/free java obfuscators on his own commercial product. I know only about one project that actually had an obfuscating step in the ant build step for releases. Do you obfuscate? And if so, why do you obfuscate? Is it r

  • Arrays of Arrays in Java 2008-08-15

    This is a nasty one for me... I'm a PHP guy working in Java on a JSP project. I know how to do what I'm attempting through too much code and a complete lack of finesse. I'd prefer to do it RIGHT. :) Here is the situation: I'm writing a small display

  • Parsing search queries in Java 2008-08-17

    I have been trying to find an easy way to parse a search query and convert it to an SQL query for my DB. I have found two solutions: Lucene: Powerful Java-based search engine, contains a query parser but it isn't very configurable and I could find a

  • copy a file from SFTP server to local system using java 2008-08-18

    What is the best way to retrieve a file from a server using SFTP (as opposed to FTPS) using Java? I'll leave the particular definition of best up to you but in my mind it should include free :) --------------Solutions------------- Another option is t

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.076 (s). 11 q(s)