3

Does anyone know of a way to use the Tooling API to determine which Apex class the current class extends from? I have looked at the SymbolTable but cannot see any indication that this information is revealed.

Thanks for the help.

Cheers!

  • Do you need to use the Tooling API? You can do this with pure Apex. Let me know and i'll post an answer that is pure Apex. – zachelrath Sep 9 '13 at 15:59
  • @zachelrath - If you would not mind sharing the code, I would appreciate it. – ImJohnMDaniel Sep 9 '13 at 19:45
  • John, if the answer given answers your question, please vote it up and mark it as accepted --- thanks! – zachelrath Sep 16 '13 at 17:01
  • 1
    @zachelrath - your answer is a fine alternative. Thanks – ImJohnMDaniel Sep 17 '13 at 21:42
2

The answer is that the Tooling API does not support this information ...at least not in v29.0

1

Here are some pure-Apex solutions for determining whether a given Apex Class extends another given Apex Class.

(Option 1) Query the ApexClass object for its Body field, and parse out the body as a string to find the class that it extends

// Query for the class definition, retrieving the class Body
ApexClass cls = [select Id,Name,Body from ApexClass where Name = 'MyApexClass' limit 1];
String body = String.valueOf(cls.Body);
String classDef = body.substring(0,body.indexOf('{'));
String classExtended;
if (classDef.contains('extends')){
    Integer extendsInitial = classDef.indexOf(' extends ');
    Integer extendsStarts = extendsInitial+9;
    Integer extendsEnds = classDef.indexOf(' ',extendsStarts);
    classExtended = body.substring(extendsStarts,extendsEnds);
    System.debug('Class ' + cls.Name + ' extends: ' + classExtended);
} else {
    System.debug('Class ' + cls.Name + ' does not extend another class');
}

You can then compare classExtended to whatever class you are wondering whether the class extends.

(Scenario 2) Use System.Type and try/catch to determine whether a given type is an instance of another type

String classToCheck = 'MyClassThatExtendsAnother';
String classExtended = 'MyBaseClass';

System.Type t = System.Type.forName(classToCheck);
MyBaseClass c;
try {
    c = (MyBaseClass) JSON.deserialize('{}',t);
} catch (Exception ex){}

if (c == null){
    System.debug('Class ' + classToCheck + ' does not extend ' + classExtended);
} else {
    System.debug('Class ' + classToCheck + ' DOES extend ' + classExtended);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.