Check if a Class Object is subclass of another Class Object in Java

前端 未结 8 1050
鱼传尺愫
鱼传尺愫 2020-11-28 20:33

I\'m playing around with Java\'s reflection API and trying to handle some fields. Now I\'m stuck with identifying the type of my fields. Strings are easy, just do myFi

8条回答
  •  误落风尘
    2020-11-28 21:12

    A recursive method to check if a Class is a sub class of another Class...

    Improved version of @To Kra's answer:

    protected boolean isSubclassOf(Class clazz, Class superClass) {
        if (superClass.equals(Object.class)) {
            // Every class is an Object.
            return true;
        }
        if (clazz.equals(superClass)) {
            return true;
        } else {
            clazz = clazz.getSuperclass();
            // every class is Object, but superClass is below Object
            if (clazz.equals(Object.class)) {
                // we've reached the top of the hierarchy, but superClass couldn't be found.
                return false;
            }
            // try the next level up the hierarchy.
            return isSubclassOf(clazz, superClass);
        }
    }
    

提交回复
热议问题