When I use System.out.println(obj.getClass())
it doesn't give me any error. From what I understand getClass()
returns a Class type.
Since println()
will print only strings, how come instead of a class, println
is getting a String?
As you probably know, every class in Java inherits from the Object class. This means that every class automatically has the method toString() , which returns a representation of the object as a String .
getClass() method returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
Java Class getName() Method The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object.
getClass() is the method of Object class. This method returns the runtime class of this object. The class object which is returned is the object that is locked by static synchronized method of the represented class.
System.out.println(someobj)
is always equivalent to:
System.out.println(String.valueOf(someobj));
And, for non-null values of someobj
, that prints someobj.toString();
In your case, you are doing println(obj.getClass())
so you are really doing:
System.out.println(String.valueOf(obj.getClass()));
which is calling the toString
method on the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With