@contract-case/java-ast

中文文档
0.0.2发布于 2025/12/14TypeScriptCommonJS近 30 天下载 112.5万

This is a temporary fork of @amplication/java-ast. It exists to get fixes for the following issues:

原始使用文档
文档目录11 节
  1. Scope and Purpose
  2. Installation
  3. Building
  4. Running unit tests
  5. Publish to npm
  6. Features
  7. Basic Usage
  8. Advanced Usage
  9. Creating Interfaces
  10. Creating Enums
  11. License

@contract-case/java-ast

This is a temporary fork of @amplication/java-ast. It exists to get fixes for the following issues:

At the time of writing, there are open PRs for each issue:

However, these haven't yet had any activity, so I'm not sure if the project is maintained.

I'm not expecting to maintain this fork long term - hopefully the PRs will merge into the original repository.

Original readme follows.


@amplication/java-ast

A library for generating Java code through an abstract syntax tree (AST) approach. This library allows you to programmatically generate Java code in a type-safe manner.

Scope and Purpose

The Java AST library is not intended to cover all Java language functionality. Instead, it focuses on the elements needed to create foundation and boilerplate code with Amplication plugins. The library provides building blocks for generating well-structured Java code for common patterns and use cases.

When more specialized or custom code is needed, the CodeBlock class can be used as a generic node that can include any code as a string:

import { CodeBlock } from '@amplication/java-ast';

// Create a custom code block for specialized logic
const customLogic = new CodeBlock(`
  // Custom Java implementation
  try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = reader.readLine()) != null) {
      processLine(line);
    }
  } catch (IOException e) {
    logger.error("Error reading file", e);
  }
`);

// Add to your class or method

Installation

npm install @amplication/java-ast

Building

Run nx build java-ast to build the library.

Running unit tests

Run nx test java-ast to execute the unit tests via Jest.

Publish to npm

In order to publish to npm @amplication/java-ast :

  1. Make sure to update the version in the package.json.
  2. Run the following:
# From the monorepo root folder
npm i

npx nx build java-ast

cd ./dist/libs/java-ast

To publish the package as "beta" run:

npm publish --access public --tag beta

To publish the package as "latest" run:


npm publish --access public
    

Features

  • Type-safe Java code generation
  • Support for all core Java constructs (classes, interfaces, enums, methods, fields, etc.)
  • Automatic import management
  • JavaDoc generation
  • Proper code formatting

Basic Usage

import {
  Class,
  Field,
  Method,
  Parameter,
  Type,
  Access,
  Annotation,
  ClassReference,
  CodeBlock,
  Writer
} from '@amplication/java-ast';

// Create a class
const userClass = new Class({
  name: 'User',
  packageName: 'com.example.model',
  access: Access.Public,
  annotations: [
    new Annotation({
      reference: new ClassReference({
        name: 'Entity',
        packageName: 'javax.persistence'
      })
    })
  ]
});

// Add fields
userClass.addField(new Field({
  name: 'id',
  type: Type.long(),
  access: Access.Private,
  annotations: [
    new Annotation({
      reference: new ClassReference({
        name: 'Id',
        packageName: 'javax.persistence'
      })
    }),
    new Annotation({
      reference: new ClassReference({
        name: 'GeneratedValue',
        packageName: 'javax.persistence'
      }),
      namedArguments: new Map([
        ['strategy', 'GenerationType.IDENTITY']
      ])
    })
  ]
}));

userClass.addField(new Field({
  name: 'username',
  type: Type.string(),
  access: Access.Private,
  javadoc: 'The username of the user.'
}));

// Add a constructor
userClass.addConstructor({
  access: Access.Public,
  parameters: [
    new Parameter({
      name: 'username',
      type: Type.string()
    })
  ],
  body: new CodeBlock({
    code: 'this.username = username;'
  })
});

// Add a method
userClass.addMethod(new Method({
  name: 'getUsername',
  access: Access.Public,
  parameters: [],
  returnType: Type.string(),
  body: new CodeBlock({
    code: 'return username;'
  })
}));

// Generate Java code
const writer = new Writer({ packageName: 'com.example.model' });
userClass.write(writer);
const javaCode = writer.toString();

console.log(javaCode);

The output will be:

package com.example.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    /**
     * The username of the user.
     */
    private String username;

    public User(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }
}

Advanced Usage

Creating Interfaces

import { Interface, Method, Type, Access } from '@amplication/java-ast';

const repository = new Interface({
  name: 'UserRepository',
  packageName: 'com.example.repository',
  access: Access.Public,
  extends_: [
    new ClassReference({
      name: 'JpaRepository',
      packageName: 'org.springframework.data.jpa.repository'
    })
  ]
});

// Add methods to the interface
repository.addMethod(new Method({
  name: 'findByUsername',
  access: Access.Public,
  parameters: [
    new Parameter({
      name: 'username',
      type: Type.string()
    })
  ],
  returnType: Type.optional(Type.reference(
    new ClassReference({ name: 'User', packageName: 'com.example.model' })
  ))
}));

Creating Enums

import { Enum, Access } from '@amplication/java-ast';

const roleEnum = new Enum({
  name: 'Role',
  packageName: 'com.example.model',
  access: Access.Public,
  javadoc: 'User roles in the system.'
});

// Add enum values
roleEnum.addValue({ name: 'ADMIN' });
roleEnum.addValue({ name: 'USER' });
roleEnum.addValue({ name: 'GUEST' });

License

MIT

版本与发布记录

@contract-case/java-ast 共发布 1 个版本,首次发布于 2025/12/14;过去 12 个月发布了 1 个版本。

版本发布日期距今
0.0.2latest2025/12/1410 个月前

关于 @contract-case/java-ast 的常见问题

@contract-case/java-ast 是什么?

This is a temporary fork of @amplication/java-ast. It exists to get fixes for the following issues:

如何安装 @contract-case/java-ast?

在项目目录运行 npm install @contract-case/java-ast,或使用 pnpm add / yarn add / bun add。

@contract-case/java-ast 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@contract-case/java-ast 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@contract-case/java-ast 可以商用吗?

@contract-case/java-ast 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@contract-case/java-ast 的下载量有多少?

根据 npm 官方下载统计,@contract-case/java-ast 在 2026/10/11 – 2026/11/09 这 30 天内被下载 1,125,114 次,日均约 37,504 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@contract-case/java-ast 还在维护吗?

最新版本 0.0.2 发布于 2025/12/14(10 个月前);至今共发布 1 个版本,其中过去 12 个月发布了 1 个;首次发布于 2025/12/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。