Dom
Dom

Reputation: 159

Java - Get a given objects name from another class

I have a basic understanding of OOP concepts, but here is a question I currently have.

Say I create this object:

Test test1 = new Test();

I then call a function within this Object

test1.toString();

And when overriding that toString() method I want to get the 'test1' object name from the main class file, so I can print it out like so...

System.out.println( "This is a test " + test1.toString() );

Prints:

This is a test test1

Thank you

Upvotes: 0

Views: 313

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533472

The name of a local variable is only meaningful at compile time. There is no way to obtain the name of a reference.

Note: the reference and the Object are two different things.

What you can do is get the name of a field, however there is no way to find from an object where the object has been assigned.

The normal way to give an Object a name, is to give a field e.g. name

Test test1 = new Test("test1");
String str = test1.getName();

For enum there is an implicit name.

enum BuySell {
    Buy, Sell;
}

BuySell bs = BuySell.Buy;
String s = bs.name(); // implicitly defined for all Enum

Upvotes: 4

Related Questions