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

前端 未结 8 1047
鱼传尺愫
鱼传尺愫 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:17

    This works for me:

    protected boolean isTypeOf(String myClass, Class superClass) {
        boolean isSubclassOf = false;
        try {
            Class clazz = Class.forName(myClass);
            if (!clazz.equals(superClass)) {
                clazz = clazz.getSuperclass();
                isSubclassOf = isTypeOf(clazz.getName(), superClass);
            } else {
                isSubclassOf = true;
            }
    
        } catch(ClassNotFoundException e) {
            /* Ignore */
        }
        return isSubclassOf;
    }
    

提交回复
热议问题