I want to calculate some metrics on Apex classes. So I need to somewhat "parse" them with the means that exist in Apex e.g. regexp patterns, groups and regions.
I want to match class declarations and public method declarations and would love to be able to directly access those parts of the matched fragment:
- Is it static, abstract or default?
- Is it a class or an interface?
- What's the methodname?
- What's the Returntype?
- What's the param list?
So the resulting code could do this:
private static Pattern classDef = Pattern.compile('???');
private static Pattern publicMethods = Pattern.compile('???');
for(ApexClass c : [SELECT NamespacePrefix, Name, ApiVersion, Status, IsValid, Body
FROM ApexClass
ORDER BY NamespacePrefix, Name]) {
// Parse class declaration
String classModifier; // abstract, static
String classType; // class, interface
String className = c.Name;
String superType; // extends, implements
String superName; // name of super class/interface
Matcher result = classDef.matcher(c.Body);
if (result.find()) {
classModifier = result.group(0);
classType = result.group(1);
superType = result.group(2);
superName = result.group(3);
...
}
// Parse class body for public methods
result = publicMethods.matcher(c.Body);
while (result.find()) {
String methodModifier = result.group(0);
String returnType = result.group(1);
String methodName = result.group(2);
String params = result.group(3);
...
}
}