views:

87

answers:

2

I use

if (clazz.getSuperclass().getName() == "java.lang.Object")

Is there a better way?

+7  A: 

if ( clazz.getSuperclass( ) == Object.class )

There are 2 problems with your original implementation:

  1. getSuperclass may return null and you get NPE when you call getName
  2. You use identity equality with a String ( == instead of equals ). Strangely enough it may work in this case as "java.lang.Object" string is probably internalized.
Alexander Pogrebnyak
+3  A: 

How about

if (clazz.getSuperclass().equals(java.lang.Object.class))
Péter Török
This may throw NPE if clazz is primitive or `java.lang.Object`. Probably `Object.class.equals( clazz.getSuperclass( ) )` is more robust. Also `java.lang.Class` is one of the classes where it's OK to use identity compare.
Alexander Pogrebnyak
@Alexander, good point, thanks. I was not _quite_ sure about the identity compare, so I used `equals` - thus getting myself bitten in the other leg :-)
Péter Török