2

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

rainman
  • 2,551
  • 6
  • 29
  • 43
  • What do you mean by the "name" of the object? The `name` property? The name of the class? The name of the variable you've assigned it to? – T.J. Crowder May 30 '15 at 14:45
  • 1
    This seems impossible. – Andrew Tobilko May 30 '15 at 14:47
  • 2
    Objects don't have names. Variables do, but objects don't. Understand that the same object referenced by the book variable can be referenced by a whole host of other variables. Which variable represents its name? Or an object can be part of an array or ArrayList and thus not be part of a "named" variable. So again, objects have no names. – Hovercraft Full Of Eels May 30 '15 at 14:48
  • 1
    Closed as a duplicate as this and similar questions have been asked many many times. I'm not sure that we need yet one more. – Hovercraft Full Of Eels May 30 '15 at 14:55

3 Answers3

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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

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();
Raphael Amoedo
  • 4,233
  • 4
  • 28
  • 37
0

Use:

book.getClass().getName();

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

maskacovnik
  • 3,080
  • 5
  • 20
  • 26