Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between getType() and getClass() in java?

Tags:

java

types

class

I used to use getType() in c# and I see it exist in Java as well.

when should I use getType() and when getClass()?

like image 656
Elad Benda Avatar asked Nov 15 '14 18:11

Elad Benda


2 Answers

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.

like image 61
DanielGibbs Avatar answered Sep 21 '22 20:09

DanielGibbs


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

like image 21
Saif Avatar answered Sep 18 '22 20:09

Saif