Need help to retrieve code from other apex classes in my apex class.

I was able to do this via the query below:

select body,bodyCrc,LengthWithoutComments from apexclass where name='AccountHandler'

But the problem is, the code is retrieved as a string without line numbers.

Any suggestions on how to retrieve the same with line numbers.

  • You'd think you could split on '\n', but they seem to be stripped out. – Adrian Larson Mar 21 '16 at 8:03
  • @AdrianLarson Wasn't a problem for me using execute anonymous. – Keith C Mar 21 '16 at 9:30
  • I guess the query editor just strips them out. @Keith – Adrian Larson Mar 21 '16 at 15:14

You can add the line numbers back in yourself using e.g.:

apexclass ac = [select body from apexclass where name='AccountHandler'];
String[] lines = ac.body.split('\n');
String[] numberedLines = new String[] {};
for (Integer i = 0; i < lines.size(); i++) {
    numberedLines.add((i + 1) + ': ' + lines[i]);
String numbered = String.join(numberedLines, '\n');

(Best to pad the numbers to a fixed width.)

Your Answer

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