Javalang: Pure Python Java Parser

0.13.0 · maintenance · verified Thu Apr 16

Javalang is a pure Python library designed for working with Java source code. It provides a lexer and parser specifically targeting Java 8, with its implementation based on the Java Language Specification. The library's current version is 0.13.0, released on March 28, 2020.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing a complete Java source file using `javalang.parse.parse()` and then traversing the resulting Abstract Syntax Tree (AST) to extract package, class, method, and field names. Error handling for common parsing issues is included.

import javalang

java_code = """
package com.example;

public class MyClass {
    // Simple field
    int myField = 10;

    public static void main(String[] args) {
        System.out.println("Hello, Javalang!");
    }
}
"""

try:
    tree = javalang.parse.parse(java_code)
    print(f"Parsed package: {tree.package.name}")
    print(f"Parsed class: {tree.types[0].name}")

    # Iterate through nodes to find methods and fields
    for path, node in tree:
        if isinstance(node, javalang.tree.MethodDeclaration):
            print(f"  Method found: {node.name}")
        elif isinstance(node, javalang.tree.FieldDeclaration):
            print(f"  Field found: {node.declarators[0].name}")

except javalang.tokenizer.LexerError as e:
    print(f"Lexer Error: {e}")
except javalang.parser.JavaSyntaxError as e:
    print(f"Syntax Error: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →