Search code examples
orientdb

In OrientDB, how to tell whether one class inherits from another in the Java API?


If you have a nested class hierarchy for your data model and you are using the SQL syntax, you can use the INSTANCEOF operator to filter your results to only objects that extend a given class. But, using the Java API, and given only the two class names, what is a good way to find out whether one class inherits from (extends) another class using the Java API? You can't just check the superClasses property if you have a situation such as this:

  V             ClassA
   \            /
  ClassB    ClassC
       \    /
       ClassD

When you retrieve the superClasses of ClassD, you will only see [ClassB, ClassC].


Solution

  • I created a function in OrientDB Studio using JavaScript, called DoesClassHaveSuperClass(). It takes two string parameters, checkClass and superClass. It uses a recursive function call to handle nested classes.

    // DoesClassHaveSuperClass()
    // Input parameters: string "checkClass", string "superClass"
    // This function looks to see whether "checkClass" inherits from "superClass",
    // either directly or indirectly.
    var schema = orient.getDatabase().getMetadata().getSchema();
    return hasSuperClass(schema, checkClass, superClass);
    
    function hasSuperClass(schema, checkClass, superClass) {
      var superClasses = schema.getClass(checkClass).getSuperClassesNames();
      if (superClasses.contains(superClass)) {
        return true;
      }
      else {
        for (var i = 0, len = superClasses.length; i < len; i++) {
          if (hasSuperClass(schema, superClasses[i], superClass)) {
            return true;
          }
        }
      }
      return false;
    }