简体   繁体   中英

Check if the superclass is java.lang.Object

I use

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

Is there a better way?

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.

怎么样

if (clazz.getSuperclass().equals(java.lang.Object.class))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM