I used to use getType()
in c# and I see it exist in Java as well.
when should I use getType()
and when getClass()
?
According to the documentation for getClass and getType:
getClass
returns "The Class object that represents the runtime class of this object."
getType
returns "a Class object identifying the declared type of the field represented by this object"
The main difference being that someObject.getClass()
will give you a class object of the runtime type of someObject
, and someField.getType()
will give you a class object of the declared type of the field that someField
refers to.
(Calling someField.getClass()
will return Field.class
because it's referring to the Field
object itself, not the field that it is referring to).
Also, while getClass
is available for every object, getType
is only available on Field
objects which are part of the reflection API.
getClass
is a method of Class Object which will be inherited to all the classes and will work same in every situation.getType
is just like some other method written on different classes for different purposes .
getClass()
Returns the runtime class of this Object. The returned Class object is the object that is locked by
static synchronized methods of the represented class.
As the documentation says
And It is universal for all the classes that will be ever written on Java
getType() Return different things on different situation
As for example
In Character method getType Returns a value indicating a character's general category.
In java.awt.Window method getType return Enum Window.Type
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