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.
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
npm install @amplication/java-ast
Run nx build java-ast
to build the library.
Run nx test java-ast
to execute the unit tests via Jest.
In order to publish to npm @amplication/java-ast
:
# 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
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;
}
}
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' })
))
}));
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' });
MIT