{"id":12739,"library":"java-parser","title":"java-parser","description":"java-parser is a JavaScript-based parser for Java source code, designed to operate without a JVM. It takes Java code as input and produces a Concrete Syntax Tree (CST) using the Chevrotain parsing toolkit. The current stable version is 3.0.1. While it is a foundational, internal component of the `prettier-plugin-java` project for formatting, it can be used independently to programmatically analyze Java code. The library offers functionality to parse raw code into a CST and then transform that CST into a more abstract AST representation. This capability makes it suitable for static analysis, code transformations, or custom tooling within JavaScript environments where JVM-based parsers are not practical or desired. Releases often align with its parent `prettier-java` monorepo updates, typically focusing on parser correctness and AST generation improvements.","status":"active","version":"3.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/jhipster/prettier-java/tree/main/packages/java-parser","tags":["javascript","typescript"],"install":[{"cmd":"npm install java-parser","lang":"bash","label":"npm"},{"cmd":"yarn add java-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add java-parser","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core parsing engine for generating the Concrete Syntax Tree (CST).","package":"chevrotain"},{"reason":"Provides the Abstract Syntax Tree (AST) definition and transformation utilities, tightly coupled within the Prettier Java ecosystem.","package":"@prettier/java-ast"}],"imports":[{"note":"The `java-parser` package is ESM-only since version 3.0.0, so CommonJS `require` statements will fail unless transpiled or run in an environment configured for ESM interoperability.","wrong":"const { parse } = require('java-parser');","symbol":"parse","correct":"import { parse } from 'java-parser';"},{"note":"`toAST` is a named export from the main package, not a default export from a subpath. It transforms the CST produced by `parse` into an AST.","wrong":"import toAST from 'java-parser/toAST';","symbol":"toAST","correct":"import { toAST } from 'java-parser';"},{"note":"LexingError is useful for catching and handling errors that occur during the tokenization phase of parsing.","symbol":"LexingError","correct":"import { LexingError } from 'java-parser';"}],"quickstart":{"code":"import { parse, toAST } from 'java-parser';\n\nconst javaCode = `\npackage com.example;\n\npublic class MyClass {\n    // This is a single-line comment\n    private String name; /* This is a multi-line comment */\n\n    public MyClass(String name) {\n        this.name = name;\n    }\n\n    public void greet() {\n        System.out.println(\"Hello, \" + name + \"!\");\n    }\n}\n`;\n\ntry {\n    // Parse the Java code into a Concrete Syntax Tree (CST)\n    const cst = parse(javaCode);\n    console.log(\"CST Root: \", cst.name);\n    // console.log(JSON.stringify(cst, null, 2)); // Uncomment for full CST\n\n    // Convert the CST to an Abstract Syntax Tree (AST)\n    const ast = toAST(cst);\n    console.log(\"AST Root Type: \", ast.type);\n    // Access package name example (assuming standard AST structure)\n    // The exact path may vary based on AST definition.\n    console.log(\"AST Package Name: \", ast.packageDeclaration?.name?.children?.Identifier?.[0]?.image || 'N/A');\n    // console.log(JSON.stringify(ast, null, 2)); // Uncomment for full AST\n\n    console.log(\"\\nSuccessfully parsed Java code and converted to AST.\");\n} catch (e: any) {\n    console.error(\"Parsing failed:\", e.message);\n    if (e.errors) {\n        e.errors.forEach((err: any) => console.error(`  - Line ${err.line}, Column ${err.column}: ${err.message}`));\n    }\n}","lang":"typescript","description":"Demonstrates how to parse a simple Java class into a Concrete Syntax Tree (CST) and then transform it into an Abstract Syntax Tree (AST) using `java-parser`."},"warnings":[{"fix":"Migrate your project to use ES Modules with `import` statements, or configure your build system (e.g., Webpack, Rollup) or Node.js environment to handle ESM. For Node.js, ensure your `package.json` includes `\"type\": \"module\"` or use `.mjs` file extensions.","message":"Version 3.0.0 of `java-parser` transitioned to being an ES Module (ESM) only package, dropping CommonJS (CJS) support. Projects using `require()` will encounter errors unless they are configured for ESM interoperability or transpiled.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Review the `@prettier/java-ast` documentation or source code for the exact AST structure in version 3.x.x. Update any code that traverses or manipulates the AST to match the new structure. Comprehensive testing of AST consumers is recommended.","message":"The Abstract Syntax Tree (AST) structure generated by `toAST` may have changed significantly in version 3.0.0 due to updates in the `@prettier/java-ast` dependency and internal parser logic improvements. Code relying on specific AST node shapes or properties will likely break.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"If you are extending the parser or creating custom Chevrotain visitors, review the Chevrotain v10 migration guide. Thoroughly test parsing edge cases and error scenarios after updating to `java-parser` v3.","message":"The underlying Chevrotain parsing toolkit was updated to v10 in `java-parser` v3. This major update in a core dependency could introduce subtle changes in parsing behavior, error reporting, or performance characteristics, especially for advanced users interacting directly with the Chevrotain API or AST visitors.","severity":"gotcha","affected_versions":">=3.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Change `const { parse } = require('java-parser');` to `import { parse } from 'java-parser';`. Ensure your environment (e.g., Node.js project) is configured for ESM, typically by adding `\"type\": \"module\"` to `package.json` or using `.mjs` file extensions.","cause":"`java-parser` is an ES Module (ESM) only package since v3, and `require()` is a CommonJS (CJS) construct.","error":"ReferenceError: require is not defined"},{"fix":"Inspect the specified line and column in your Java code for syntax errors. Ensure the Java code conforms to a standard Java grammar supported by the parser. If the code is valid Java, check `java-parser`'s capabilities and reported Java language level support.","cause":"The input Java code contains a syntax error that the parser cannot resolve, or the `java-parser` library does not support the specific Java language feature or syntax used.","error":"Parsing failed: Expected token of type --> 'X' <-- but found --> 'Y' <-- at line <num>, column <num>."},{"fix":"Log the generated AST (`console.log(JSON.stringify(ast, null, 2));`) to understand its current structure. Adjust your AST traversal and manipulation logic to match the actual shape of the AST generated by `java-parser` version 3.x.x.","cause":"Your code is attempting to access properties of the Abstract Syntax Tree (AST) that do not exist or have changed their structure, often due to an update to `java-parser` or `@prettier/java-ast`.","error":"TypeError: Cannot read properties of undefined (reading 'children') or similar AST traversal errors"}],"ecosystem":"npm"}