javaobjectname

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


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


Solution

    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).