Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

compare two classes with .getSimpleName()

 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a difference between this:




and that:



should I use getSimpleName to compare two classes?

 
Maneesh Godbole
Saloon Keeper
Posts: 11027
12
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
getClass does a class comparison where as the other does a String comparison. Would't the getSimpleName() return the name without the package?(Am not sure)
If you are doing, what I think you are doing, I would suggest use the instanceof operator...unless I have misunderstood your question
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maneesh Godbole wrote:Would't the getSimpleName() return the name without the package?(Am not sure)

Yes it would. Which can be a danger; consider java.util.List and java.awt.List. Comparing the full class name would really find those two unequal.

The only time when s.getClass().equals(MyClass.class) would return false even though s.getClass() is a MyClass Class object, is when two different class loaders were used. However, since MyClass.class is resolved at compile time, the class itself is loaded by the system class loader. That means that if s.getClass() would return a MyClass Class object as well, it will be found through the same class loader. Hence, s.getClass().equals(MyClass.class) will return true in that case.

Note that you can also use == for Class object comparison since Class is final and inherits equals from Object, which uses == for equality.

If you are doing, what I think you are doing, I would suggest use the instanceof operator...unless I have misunderstood your question

Using this type of class comparison is stricter. For instance, if s is a java.util.Stack, then "s instanceof Vector" will return true while "s.getClass() == Vector.class" will not.
 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
okay, thanks everybody!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic