File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes compare two classes with .getSimpleName() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "compare two classes with .getSimpleName()" Watch "compare two classes with .getSimpleName()" New topic
Author

compare two classes with .getSimpleName()

nimo frey
Ranch Hand

Joined: Jun 28, 2008
Posts: 580
Is there a difference between this:




and that:



should I use getSimpleName to compare two classes?

Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10255
    
    8

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


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
nimo frey
Ranch Hand

Joined: Jun 28, 2008
Posts: 580
okay, thanks everybody!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: compare two classes with .getSimpleName()