Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how can I get the type of the object ?

 
Meir Yan
Ranch Hand
Posts: 599
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello
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
Posts: 536
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
getClass()
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15435
41
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic