how can i get an object name when it is created in java?

6.6k Views Asked by At

when an object is created how can i get the name of that object ??

for example let's consider a class Book:

public class Book {
  private String name;
  private int pages;

  public Book(String name, int pages) {
        this.name = name;
        this.pages = pages;
  }

  }
// now i create an object of this class
Book book = new Book("Java",100);

i want to get the name of the object created that is "book", is there any way to get it ? i tried the toString(), function and it does not work it prints something like this: @3d4eac69

3

There are 3 best solutions below

2
On BEST ANSWER
  1. If you mean the name property, you can't with your code as written. You'd need to either make name public, or provide a public getter for it

  2. If you mean the name of the class, it would be

    book.getClass().getName()
    
  3. If you mean the name of the variable you've assigned it to (book), you can't, that isn't information available at runtime (outside of a debug build and debugger introspection).

0
On

You have to create the getter method in Book class. Would be like:

public String getName() {
    return this.name;
}

And then you would call:

book.getName();
2
On

Use:

book.getClass().getName();

Every object in Java has getClass() method:
getClass() documentation
And every Class object has its name:
getName() documentation