parsing java files

Paul Boddie paul at boddie.org.uk
Thu Sep 21 17:20:28 EDT 2006


stéphane bard wrote:
> hello
> i would like to parse java files an detect
> class name's, attributes name's type's and visibility (and or list of
> methods).
>
> is there any module who can parse easily a java file without using
> (jython)?

There are probably a number of standard parser solutions which can
expose such information. However, another solution is that provided by
the javaclass package:

import javaclass.classfile # http://www.python.org/pypi/javaclass

# Read the contents of the compiled class.

f = open("org/w3c/dom/Element.class", "rb")
s = f.read()
f.close()

# Process the class data.

c = javaclass.classfile.ClassFile(s)

# Obtain the internal name of the class.

name = unicode(c.interfaces[0].get_name()) # u'org/w3c/dom/Node'
for m in c.methods:

    # Obtain each method name and access details.

    method_name = unicode(m.get_name()) # eg. u'getTagName'
    is_public = m.access_flags & javaclass.classfile.PUBLIC

Obviously, this is more convoluted than it needs to be, but the
original purpose of the module employed is to assist in translating
Java class data to other forms - notably Python bytecode - although
such experiments haven't been continued by myself for quite some time.
The class decoding part illustrated above should be quite usable,
however.

Paul




More information about the Python-list mailing list