List methods from a source file


Sometimes source files can become quite large. This is common mostly in C. But this may happen in other languages too. It makes working with these files particularly hard. Off-course there are IDEs which lists method and properties and what not. But there is a fun way to do the same stuff using python. The regex for the signature of Java methods is, (public|protected|private|static|\s) +[\w\\[\]]+\s+(\w+) *\([^\)]*\) *(\{?|[^;]) You can use this regex in python and have some fun summarizing your Java source files. Here is the script: on Github and via Gist,

methodSignature = '(public|protected|private|static|\s) +[\w\<\>\[\]]+\s+(\w+) *\([^\)]*\) *(\{?|[^;])'
import traceback
def main():
import getopt, sys, re
try:
options, args = getopt.getopt(sys.argv[1:], 'i:h', ['input=','help'])
except getopt.GetoptError as err:
# print help information and exit:
print(err) # will print something like 'option -a not recognized'
sys.exit(2)
javaFile = ''
# read args
for opt, arg in options:
if opt in ('-i', '--input'):
javaFile = arg
if javaFile is '': javaFile = sys.argv[1]
try:
with open(javaFile, "rU") as file:
lines = file.readlines()
print '//',javaFile
print '//',len(lines), 'lines of code'
methods = {}
for line in lines:
try:
m = re.search(methodSignature,line)
if len(m.group(0))>0 :
methodLine = m.group(0)
methodLine = methodLine.replace(' {','')
access, type, methodSig = methodLine.split(' ',2)
# print m.group(0)
methods[methodSig] = (access, type)
except: a=1
#print '\nSorted list\n'
for methodSig in sorted(methods.keys()):
(access,type) = methods[methodSig]
print '{} {} {};'.format(access,type,methodSig)
except Exception, e:
traceback.print_exc()
if __name__ == '__main__':
main()
view raw ListMethods.py hosted with ❤ by GitHub
Cheers!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.