Java - pass a pointer to an object to a function

14,360

Solution 1

If you really want doStuff to return two values: There may well be a better way to design this. Nevertheless, if you've decided that having doStuff return two values is really the best design, it can be done with a simple helper class:

static class MyClassAndBoolean {
    public MyClass obj;
    public boolean b;
    public MyClassAndBoolean(MyClass obj, boolean b) { this.obj = obj; this.b = b; }
}

and then change doStuff's return type to MyClassAndBoolean. This is one of the very few cases where I think public fields in a class are OK. Since you're defining a simple class just to use as a function result, rather than representing a coherent concept, the usual concerns about defining accessors instead of exposing fields, etc., don't really apply. (P.S. I just guessed at boolean for the other type, but it can be anything, of course.)

Another workaround:

MyClass[] obj = new MyClass[1];
result = doStuff(obj);

Change doStuff's parameter type to MyClass[], and have it stuff the new object into parameter[0]. I do see this idiom used in some of the Java and Android library methods.

Solution 2

Why not simply:

MyClass object = doStuff();

which is much more intuitive IMHO. Otherwise you have to pass a reference (not pointer!) to a container object to your method, as you've identified. That's not a common pattern in the Java world.

Share:
14,360
Christian Schnorr
Author by

Christian Schnorr

Seasoned software engineer with 9 years of experience in iOS development, specializing in building complex user interfaces and architecting large-scale applications used by millions of people every month. WWDC 2017 scholar. Currently finishing my Master's degree at Karlsruhe Institute of Technology (KIT) with a focus on theoretical computer science, compiler construction, and computer graphics. Major projects I have worked on: Things Busradar Chrono24 LinkedIn: https://www.linkedin.com/in/jenox/

Updated on June 04, 2022

Comments

  • Christian Schnorr
    Christian Schnorr almost 2 years

    What I want to achieve is something like this:

    MyClass object = null;
    doStuff(&object);
    
    // `object` can now be non-null
    

    What I'm currently doing is this, but I think there must be a better way to achieve this behavior in Java:

    MyClassPointer pointer = new MyClassPointer(null);
    // pointer.object is null
    doStuff(pointer);
    
    // pointer.object can now be non-null