Getting the name of the instance

is there a way of within an object to get the name of the instance it is running the code for.

Hi,

Welcome to the community! :wink:

What dou you exactly mean when you say “name of the instance”? Do you mean the name of the class or a name attribute ? (or the name of the variable that holds the object?)

If you want the name of the class for an object, you can use this :

object.getClass().getSimpleName()
abstract class GetName {
  String getName() {
    return this.getClass().getSimpleName();
  }
}

class Test extends GetName {}
class Other extends GetName {}

Test test = new Test();
println(test.getName());

Other other = new Other();
println(other.getName());

// OUTPUT
// Test
// Other
1 Like

thank you for the response, I do mean the name of the variable that holds the obkect.

That is sadly not possible. And when you think about, it becomes quite clear why.

Imagine the following piece of code:

class GetName {

  String getName() {
    //... return the name of the object
  }

}

void setup() {
  GetName instance1 = new GetName();
  GetName instance2 = instance1;
}

Now two variables contain the same instance of GetName. What should getName() return in this case? You could argue that it should return instance1, because that is the variable to initially contain the object, but what if we set instance1 to something else? Should getName() then return instance2?

It would just get really confusing and is (partially) therefore impossible.

I recommend you think about what you want to do again, and then try to come up with a simpler solution. :wink:

1 Like

Not directly as has been said.

Basically as a work-around, you can pass a String to the constructor that can contain the name of the variable or some kind of ID so you can work with it. See below.

Maybe you can tell us what you want to achieve with the name of the instance and then we think of what to do.

Warm regards,

Chrisir :wink:


Example




// =============================================================================

class GetName {

  String nameTest=""; 

  // constr 
  GetName( String nameTest_) {
    nameTest = nameTest_;
  }// constr 

  String getName() {
    // return the name of the object
    return nameTest;
  }
}

// =============================================================================

void setup() {
  //
  size(340, 340);

  GetName instance1 = new GetName("instance1");
  GetName instance2 = new GetName("instance2");

  println(instance1.getName());
  println(instance2.getName());
}//func 
//

1 Like