1. java-parser
Java Parser in JavaScript
java-parser
Package: java-parser
Created by: jhipster
Last modified: Mon, 25 Mar 2024 09:33:22 GMT
Version: 2.3.0
License: Apache-2.0
Downloads: 1,070,817
Repository: https://github.com/jhipster/prettier-java

Install

npm install java-parser
yarn add java-parser

npm

java-parser

A Java Parser implemented in JavaScript using the Chevrotain Parsing ToolKit.
It outputs a Concrete Syntax Tree, rather than an Abstract Syntax Tree.

Currently the main focus of this project is to be used in implementing a prettier Java plugin.
But it could also be used as the basis for other Java related tools in the JavaScript ecosystem.

Installation

 npm install java-parser --save-dev

or

 yarn add java-parser --dev

Usage

Parsing

 const { parse } = require("java-parser");
const javaText = `
public class HelloWorldExample{
  public static void main(String args[]){
    System.out.println("Hello World !");
  }
}
`;

const cst = parse(javaText);
// explore the CST

Traversing the CST

See relevant Chevrotain documentation on CST Traversal.

 const {
  BaseJavaCstVisitor,
  BaseJavaCstVisitorWithDefaults
} = require("java-parser");

// Use "BaseJavaCstVisitor" if you need to implement all the visitor methods yourself.
class LambdaArrowsPositionCollector extends BaseJavaCstVisitorWithDefaults {
  constructor() {
    super();
    this.customResult = [];
    this.validateVisitor();
  }

  lambdaExpression(ctx) {
    // Collects all the starting offsets of lambda arrows in lambdas with short (no parenthesis)
    // single argument lists: e.g:
    // - n -> n*n (will be collected)
    // - (n) -> n*n (not collected)
    if (ctx.lambdaParameters[0].children.Identifier) {
      this.customResult.push(ctx.Arrow[0].startOffset);
    }
  }
}

const lambdaArrowsCollector = new LambdaArrowsPositionCollector();
// The CST result from the previous code snippet
lambdaArrowsCollector.visit(cst);
lambdaArrowsCollector.customResult.forEach(arrowOffset => {
  console.log(arrowOffset);
});

RELATED POST

Enhancing Vue.js Development: Harnessing the Potential of Vue-Loader

Enhancing Vue.js Development: Harnessing the Potential of Vue-Loader

Simplify Data Validation in Vue.js: A Step-by-Step Guide to Using Regex

Simplify Data Validation in Vue.js: A Step-by-Step Guide to Using Regex

Troubleshooting Made Easy: Common Issues and Solutions with vue-loader Without vue-cli

Troubleshooting Made Easy: Common Issues and Solutions with vue-loader Without vue-cli

Optimizing Webpack 4 with Vue CLI 3: Disabling the Cache-Loader

Optimizing Webpack 4 with Vue CLI 3: Disabling the Cache-Loader

Step-by-Step Guide: How to Add a Function to Your Vuex Plugin

Step-by-Step Guide: How to Add a Function to Your Vuex Plugin