Code Generation
Generate Java bindings from a compiled DAR file:Generated Class Structure
For a Daml template:Licenseclass — Represents the template payload with fieldsprovider,user,description, andexpiresAtLicense.ContractIdclass — A typed contract identifier forLicenseinstancesLicense.Renewclass — Represents theRenewchoice argument with anewExpiryfield- Serialization methods —
toValue()andfromValue()for converting between Java objects and the Ledger API’s value representation
gRPC Client Setup
The generated classes work with the gRPC Ledger API client. Connect to a validator:Submitting Commands
Create a contract using the generated class:Processing Events
When reading transaction events from the Ledger API stream, usefromValue() to deserialize contract payloads:
Maven / Gradle Dependency
Add the generated code to your build. In the cn-quickstart project, Gradle handles code generation and compilation as part of the build process. For a Gradle project, add the generated source directory:pom.xml:
Reference Documentation
The full Javadoc for the Daml Java bindings library is published with each Daml SDK release. The generated classes follow the same patterns documented there.Related Pages
- dpm codegen-java reference — Command options and flags
- TypeScript bindings — Alternative bindings for TypeScript/JavaScript
- Backend development — Patterns for building Canton backends in Java
Daml Codegen for Java
Use the Daml Codegen for Java (dpm codegen-java) to generate Java classes representing all Daml data types defined in a Daml Archive (.dar) file. These classes simplify constructing the types required by the Java gRPC bindings for the gRPC Ledger API; for example, com.daml.ledger.api.v2.CreateCommand and com.daml.ledger.api.v2.ExerciseCommand. They also provide JSON decoding utilities, making it easier to work with JSON when using the JSON Ledger API.
See How to work with contracts and transactions in Java for details on how to use the generated classes. See the sections below for guidance on setting up and invoking the codegen.
Install
Install the Daml Codegen for Java by installing DPM.Configure
To configure the Daml Codegen, choose one of the two following methods:- Command line configuration: Specify all settings directly in the command line.
- Project file configuration: Define all settings in the
daml.yamlfile.
Command line configuration
To view all available command line configuration options for Daml Codegen for Java, rundpm codegen-java --help in your terminal:
Project file configuration
Specify the above settings in thecodegen element of the Daml project file daml.yaml.
Here is an example:
sdk-version: 3.4.9
name: quickstart
source: daml
init-script: Main:initialize
parties:
- Alice
- Bob
- USD_Bank
- EUR_Bank version: 0.0.1 exposed-modules:
- Main dependencies:
- daml-prim
- daml-stdlib codegen: java: package-prefix: com.daml.quickstart.iou output-directory: java-codegen/src/main/java verbosity: 2
Operate
Run the Daml Codegen using project file configuration with: $ dpm codegen-java or using command line configuration with: $ dpm codegen-java ./.daml/dist/quickstart-0.0.1.dar=com.daml.quickstart.iou —output-directory=java-codegen/src/main/java —verbosity=2References
Generated Java code
Daml primitives to Java types
Daml built-in types are translated to the following equivalent types in Java:| Daml type | Java type | Java Bindings Value type |
|---|---|---|
Int | java.lang.Long | Int64 |
Numeric | java.math.BigDecimal | Numeric |
Text | java.lang.String | Text |
Bool | java.util.Boolean | Bool |
Party | java.lang.String | Party |
Date | java.time.LocalDate | Date |
Time | java.time.Instant | Timestamp |
List or [] | java.util.List | DamlList |
TextMap | java.util.Map Restricted to using String keys. | DamlTextMap |
Optional | java.util.Optional | DamlOptional |
() (Unit) | None since the Java language does not have a direct equivalent of Daml’s Unit type (), the generated code uses the Java Bindings value type. | Unit |
ContractId | Fields of type ContractId X refer to the generated ContractId class of the respective template X. | ContractId |
Escaping rules
To avoid clashes with Java keywords, the Daml Codegen applies escaping rules to the following Daml identifiers:- Type names (except the already mapped built-in types)
- Constructor names
- Type parameters
- Module names
- Field names
$ to the name. For example, a field with the name import will be generated as a Java field with the name import$.
Generated classes
Every user-defined data type in Daml (template, record, and variant) is represented by one or more Java classes as described in this section. The Java package for the generated classes is the equivalent of the lowercase Daml module name.Person is generated:
Name is generated:
Templates
The Daml Codegen generates the following classes for a Daml template:TemplateName Represents the contract data or the template fields. TemplateName.ContractId Used whenever a contract ID of the corresponding template is used in another template or record, for example:data Foo = Foo (ContractId Bar). This class also provides methods to generate anExerciseCommandfor each choice that can be sent to the ledger with the Java Bindings. TemplateName.Contract Represents an actual contract on the ledger. It contains a field for the contract ID (of typeTemplateName.ContractId) and a field for the template data (of typeTemplateName). With the static methodTemplateName.Contract.fromCreatedEvent, you can deserialize a CreatedEvent to an instance ofTemplateName.Contract.
BarBar.ContractIdBar.ContractBar.CreateAndBar.JsonDecoder$Bar.Exercises
Variants (a.k.a. sum types)
A variant or sum type is a type with multiple constructors, where each constructor wraps a value of another type. The generated code is comprised of an abstract class for the variant type itself and a subclass thereof for each constructor. Classes for variant constructors are similar to classes for records.Enums
An enum type is a simplified sum type with multiple constructors but without argument nor type parameters. The generated code is standard java Enum whose constants map enum type constructors.Parameterized types
This section is only included for completeness. The
fromValue and toValue methods would typically come from a template that does not have any unbound type parameters.Attribute, used by the BookAttribute type for modeling the characteristics of the book:
Attribute a data type:
Convert a value of a generated type to a Java Bindings Value
To convert an instance of the generic type Attribute to a Java Bindings Value, call thetoValue method and pass a function as the toValuea argument for converting the field of type a to the respective Java Bindings Value. The name of the parameter consists of toValue and the name of the type parameter, in this case a, to form the name toValuea.
Below is a Java fragment that converts an attribute with a java.lang.Long value to the Java Bindings representation using the method reference Int64::new.
If the Daml type is a record or variant with more than one type parameter, you need to pass a conversion function to the
toValue method for each type parameter.Create a Value of a generated type from a Java Bindings Value
Analogous to thetoValue method, to create a value of a generated type, call the method fromValue and pass conversion functions from a Java Bindings Value type to the expected Java type.
Non-exposed parameterized types
If the parameterized type is contained in a type where the actual type is specified (as in theBookAttributes type above), then the conversion methods of the enclosing type provides the required conversion function parameters automatically.
Convert optional values
The conversion of the JavaOptional requires two steps. The Optional must be mapped in order to convert its contains before to be passed to DamlOptional::of function.
Optional, one must use the containers method toOptional. This method expects a function to convert back the value possibly contains in the container.
Convert collection values
DamlCollectors provides collectors to converted Java collection containers such asList and Map to DamlValues in one pass. The builders for those collectors require functions to convert the element of the container.
toList or toMap. Those methods expect functions to convert back the container’s entries.
Daml interfaces
From this Daml definition:toInterface is generated. An unsafeFromInterface is also generated to make the unchecked conversion in the other direction.