The moose likes Beginning Java and the fly likes how can I get the type of the object ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how can I get the type of the object ?" Watch "how can I get the type of the object ?" New topic

how can I get the type of the object ?

Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
if I have some variable and I like to know what is the stype of this variable
if there any "typeOf" method that gives me that info?
Richard Green
Ranch Hand

Joined: Aug 25, 2005
Posts: 536

MCSD, SCJP, SCWCD, SCBCD, SCJD (in progress - URLybird 1.2.1)
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15080

You can use getClass() to get the java.lang.Class object that represents the type of the object.

If you just want to know if an object is an instance of or extends a certain class, or implements a certain interface, you can use the instanceof keyword.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
The above answers (suggesting getClass() and instanceof) are quite correct.

But, as this is the beginner forum, I thought I'd add a comment on use and misuse of these features.

Java is an object-oriented language (some would say not 100% so, but...). One therefore has powerful features like polymorphism available, to make objects of different types behave differently when sent the same message (method call). One should use those object-oriented features as much as possible.

It is usually bad practice to write code that conditionalises (if, switch etc.) on the type of an object. As much as possible, this should be replaced by something more object-oriented.

It's not a hard-and-fast rule. Although some Ranchers may disagree, I favour pragmatism. If a particular problem can be solved much quicker by using instanceof than by refactoring to use polymorphism, then it may be OK to use instanceof. But don't get too much into the habit.

If you were thinking of using getClass() or instanceof in an "if" or "switch" statement, you should probably go back and revisit your design.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
I agree. Here's the link:
subject: how can I get the type of the object ?
jQuery in Action, 3rd edition