returning declared object name

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rotaryfreak
    New Member
    • Oct 2008
    • 74

    returning declared object name

    Hi,

    when i create an object, is there a way to return the name of that declared object? for example, if i create

    ClassObject demo = new ClassObject();

    how can i return the name of my object, namely "demo" as a string?

    i've tried playing around with the fact that i can obtain the class name from my object, but i can not seem to find any methods that i need... can anyone guide me please?

    thanks
    joe
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    Read about Introspection, you could wrap all your classes in another class, let's say AllObjects, and investigate that class.
    Code:
     
    Class AllObjects
    {
     ClassObject demo = new ClassObject();
     ClassObject demo2 = new ClassObject();
     ...
    }
    
    ...
    foo = new AllObjects();
    System.out.println(foo.getClass().getFields());
    ...


    But probably what you want is much easier to achieve:
    Just pass a name for the constructor and write a getName() method!
    Code:
     
    ClassObject demo = new ClassObject("myName");
    ...
    String name= demo.getName();
    ...
    
    Class ClassObject()
    {
      public String name;
     public void ClassObject(String name)
     {
       this.name=name;
     }
     public string getName()
     {
       return name;
     }
    }

    Comment

    • rotaryfreak
      New Member
      • Oct 2008
      • 74

      #3
      thank you so much! extremely helpful!

      Comment

      Working...