is there a method to find the name of an object within a constructor?

It is a bit difficult to understand what you are saying because your examples clearly don’t do what you are saying. (For instance TestExample.array[0] = "exelement" is just saving a string, and you can’t resolve that to a variable.)

In fact, I’m pretty sure that the variables are a red herring too1. What you actually need is something like this:

// Simplistic incorrect version ...
public class Element {
    private static List<Element> allElements = new ArrayList<>();

    public Element() {
        ...
        allElements.add(this);
    }

    public void update() { ... } 

    public static void updateAll() {
        for (Element e: allElements) {
            e.update();
        }
    }
}

The above has a couple of problems. Firstly the use of static is liable to be a memory leak unless you either have a reliable way to clean out any elements that are no longer needed, or you use a reference type so that the GC can break the links. The second issue is that your example is apparently using an inner class.

So using an inner class, it might look like this:

public class Outer {
    private List<Element> allElements = new ArrayList<>();

    public class Element {
        
        public Element() {
            ...
            allElements.add(this);
        }

        public void update() { ... } 
    }

    public void updateAll() {
        for (Element e: allElements) {
            e.update();
        }
    }
}

Now … if the Outer instance becomes unreachable, so do any Element objects that are only reachable via allElements.


1 – But if the variables are critical, then I’m afraid you are out of luck. Java doesn’t provide a way to either take the address of a variable, or use reflection to lookup a local variable. This is what @Louis Wasserman is saying in his answer.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top