15

How do I print the variable name holding my object?

For example, I have:

myclass ob=new myclass()

How would I print "ob"?

NotMe
  • 87,343
  • 27
  • 171
  • 245
Bipin Sahoo
  • 201
  • 1
  • 2
  • 6
  • 3
    @bipin, is this homework? What have you tried? – Brad Oct 18 '10 at 12:42
  • 4
    what do you mean by "my object name" ? – jmj Oct 18 '10 at 12:42
  • 1
    hi brad, i want to know,can we print object name in our program. – Bipin Sahoo Oct 18 '10 at 12:55
  • 1
    This question is absolutely confusing. I'm not quite sure why Jon Skeet gets the check box here. Of course, I'm not entirely sure the question. – Erick Robertson Oct 18 '10 at 12:56
  • Bipin, are you asking how to print the class name of the object, or how to print the name of the variable that refers to the object? – Jeff Oct 18 '10 at 13:25
  • 1
    myclass ob=new myclass(); //i want to print "ob" in my console.that is name of the variable that refers to that object. – Bipin Sahoo Oct 18 '10 at 13:39
  • @Bipin: you should edit your question, to specify what exactly do you mean as "Object name". If you are referring to the variable name, as your last comment seems to indicate, it has nothing to do with an "object name", as the original question says – Tomas Narros Oct 18 '10 at 13:49
  • 1
    hi friend, using this we can print class name also,then what is need of object.getClass().getName().please tell me programmatically can it be possible to print the object name. – Bipin Sahoo Oct 18 '10 at 14:19
  • The variable name exists for your convenience as a programmer. It is there to give meaning to your code so that you, a human, can read and understand it. The computer doesn't need a name. It doesn't care what variable name you use. So, as Jon Skeet said, there's no such thing as a name for an object from the computer's perspective. Since you're the only one who knows/needs the variable name, if you want to print it, then just type it out yourself like BalusC said in the recent comment. – Jeff Oct 18 '10 at 14:41
  • I'm not sure why anyone is confused at all or being so condescending to the asker. The person is asking how you print the variable name assigned to an object. – user3932000 Mar 10 '17 at 02:11
  • @BalusC ArrayList of `myclass`es. Each has a variable name attached to it. How would you return the variable name of a `myclass` at a certain index without defining some new field for the entire class? Or is that absolutely and inherently impossible in the language of Java, as intended by James Gosling himself? – user3932000 Mar 10 '17 at 02:15

11 Answers11

21

Objects don't have names, unless you happen to be using a class which allows each object to be given one (e.g. via a variable retrieved with getName()).

In particular, the name of any particular variable used to refer to an object is completely unknown to the object itself. So you can't do:

Object foo = new Object();
// There's no support for this
String name = foo.getName(); // expecting to get "foo"

(Bear in mind that several variables could all refer to the same object, and there don't have to be any named variables referring to an object.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

To print the object type name:

System.out.println(myObject.getClass().getName());
Tomas Narros
  • 13,390
  • 2
  • 40
  • 56
3

Workaround. If you want the object name then you can initialize at constructor.

//in class myClass

private String objName;

myClass(String objN)
{
    this.objName = objN;
..
}
public String getObjName() {
    return objName;
}
//in main()
.
.
.
myclass ob = new myclass("ob"); //any other variables accessing this object 
                              //eg. temOb = ob get the same object name "ob"
System.out.println("object name is: " + ob.getObjName());
myclass ob1 = new myclass("ob1");
System.out.println("object name is: " + ob1.getObjName());
RamenChef
  • 5,557
  • 11
  • 31
  • 43
2

System.out.println(); Is the command used to print out to the console.

So if you have your own class that you created and instantiated, you could do:

MyObject obj = new MyObject();
System.out.println(obj);

and that would print out the toString() implementation of MyObject. The default implementation is not very interesting, so for useful info, you would have to override toString().

RamenChef
  • 5,557
  • 11
  • 31
  • 43
willcodejavaforfood
  • 43,223
  • 17
  • 81
  • 111
2

Slightly more complete (but essentially the same as above):

  1. If you have an object: object.getClass().getName() will give you the fully qualified name of the object (i.e.package.className. For example, String thing = new String(); thing.getClass().getName() will return "java.lang.String".
  2. If you have a class name: className.class.getName() will give you the fully qualified name of the object (i.e.package.className. For example. String.class.getName() will return "java.lang.String".

Print it how ever you want. Perhaps using System.out.println().

The name of the variable is compile time information that is not typically stored after compilation. The variable name is stored if you compile with debugging information.

In mamy contexts, it is a ridiculous request to want to print the name of a variable, but if you really need to do that, read up on java debugging information.

DwB
  • 37,124
  • 11
  • 56
  • 82
1

Try reflection + hash code. E.g.:

String hashcode = ob.hashCode();
String obName;
java.lang.reflect.Field[] fields = 
ob.getClass().getDeclaredFields();

for( final  java.lang.reflect.Field field : fields )
{
  if( field.hashCode().equals(hashcode) )
  {
    obName = field.getName();
    break;
  }
}
System.out.println(obName);
JPNoyola
  • 11
  • 2
0

I'm assuming you want a way to "print" an object, in which case, you'll first want to override the toString() method for your object. This will allow you to specify what an object of your type returns when you call toString().

Then, you can simply do System.out.println(MyObject);

This will implicitly call MyObject's toString().

Tyler Treat
  • 14,640
  • 15
  • 80
  • 115
0

You can't get the name of object reference. Instead you can get its hashcode or counter. I solve this problem as follows:

class ObjectName
{
    static int num;
    ObjectName()
    {
     num++;
    }

    public int getObjectCount()
    {
        return num;
    }
    public static void main(String[] args) {
        ObjectName ob1=new ObjectName();
        System.out.println(ob1.getClass().getName()+" "+ob1.getObjectCount());
        ObjectName ob2=new ObjectName();
        System.out.println(ob1.getClass().getName()+" "+ob1.getObjectCount());
    }
}

Output:

ObjectName 1
ObjectName 2
jrtapsell
  • 6,719
  • 1
  • 26
  • 49
0

This achieves the required result, but it is a bit of a fudge, in that if the string returned by toString() is to actually reflect the name of your variable (which of course, only you, as the coder will know), you have to use the convention that the method uses i.e. in this implementation, because the returned string is in the format ClassName+counter, you have to name your variable using that format: myClass1, myClass2, etc. If you name your variable in some other way (e.g. className+A/B/C etc or someRandomVariableName) although the return string would remain as implemented by the toString() method i.e. returning myClass1, myClass2, etc, it wouldn't reflect the variable name you have actually used in your code.

class myClass {

    private static int counter = 1;
    private String string;
    private int objCounter;

    myClass(String string) {
        this.string = new String(string);
        objCounter = counter;
        counter++;
    }

    @Override
    public String toString() {
        return this.getClass().getName() + objCounter + ": " + this.string;
    }

    public static void main(String[] args) {
        myClass myClass1 = new myClass("This is the text for the first object.");
        myClass myClass2 = new myClass("This is the text for the second object.");
        System.out.println(myClass1);
        System.out.println(myClass2);
    }

}
0
import java.lang.reflect.*;

public class myclass {
    private myclass ob;

    public static void main(String args[]) {
            Field fd[] = myclass.class.getDeclaredFields();
            for (int i = 0; i < fd.length; i++) {
                  System.out.println(fd[i].getName());
            }
    }
}
StardustGogeta
  • 3,331
  • 2
  • 18
  • 32
-1

I know it's too late)) but It here is a method like getSimpleName().

In this case :

myclass ob=new myclass()
System.out.println(ob.getClass().getSimpleName())

System output: ob