13

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

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

3

2 Answers 2

22

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.

3
  • what is the difference between Field.class and Field. getClass() ? Commented Dec 23, 2014 at 7:51
  • 1
    Field.class is the Field class. Field.getClass() isn't possible because you can only call getClass on instances. Commented Dec 23, 2014 at 10:04
  • what is the difference between someField.class and someField.getClass() ? Commented Dec 23, 2014 at 12:13
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.