Ubuntu insights, Programming in groovy, java, et als!

Monday, January 23, 2012

Find Source code Line Numbers of Methods at Runtime


Comparing a source file and a runtime equivalent object of the class, here is a ten liner groovy script that determines the line numbers of every method inside a class. A plausible approach to do this in java is is to throw a stacktrace explicitly wherever needed and examine it to determine the line number at the point of execution. This I find is too clumsy a way. One can also take an other approach by parsing the source code file, creating a tree node structure and manipulate it but then the problem with this approach is that one has to reinvent the whole wheel again.

Groovy's dynamism comes to rescue here exposing the runtime object to the programmer during execution. At runtime, one can inspect an object, study its methods and properties and manipulate them as per the need. This can also be done in java using the Reflection API but I find it too monstrous and verbose. I resort to groovy instead. Here's the ten liner script for the same.

//supply the source file path, the only input to the script
def sourceFilePath = 'C:\\Temp\\GroovyUtils\\Sample.groovy'

//a map that stores method names vs line numbers as key val pairs
def methodToLineMap = [:]

//find all the methods of the Sample class and assign default line number as 0 first.
def listOfMethods = new Sample().metaClass.methods*
listOfMethods .name.sort().unique().each{
    methodToLineMap.put(it,0)
}


//parse src file to find the line numbers of methods & store line number in the methodMap
def idx = 0
new File(sourceFilePath).eachLine{ line ->
    idx++
    methodToLineMap.keySet().each{method ->
        if(line.contains(method)){
            methodToLineMap[method] = idx
        }
    }
}

//print the elements of method vs line number map
methodToLineMap.each{
    if(it.value!=0)
        println it
}

PS : You can also supply a java source code file (in sourceFilePath) to find out the line numbers of the java class's methods but ensure that the .class file is on the classpath while running the script.

1 comments:

Sakahayang Kang Asep said...

thanks for your share

Post a Comment