Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.canton.network/llms.txt

Use this file to discover all available pages before exploring further.

The Java bindings produce type-safe classes from your compiled Daml packages. These classes let you create contracts, exercise choices, and process ledger events in Java without manually constructing gRPC messages or JSON payloads.

Code Generation

Generate Java bindings from a compiled DAR file:
dpm codegen-java .daml/dist/my-project.dar -o generated-java
This produces Java source files organized by Daml module. Each Daml template becomes a Java class, and each choice becomes a nested class with typed fields.

Generated Class Structure

For a Daml template:
template License
  with
    provider : Party
    user : Party
    description : Text
    expiresAt : Time
  where
    signatory provider
    observer user

    choice Renew : ContractId License
      with newExpiry : Time
      controller user
      do create this with expiresAt = newExpiry
The code generator produces:
  • License class — Represents the template payload with fields provider, user, description, and expiresAt
  • License.ContractId class — A typed contract identifier for License instances
  • License.Renew class — Represents the Renew choice argument with a newExpiry field
  • Serialization methodstoValue() and fromValue() 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:
ManagedChannel channel = ManagedChannelBuilder
    .forAddress("localhost", 2901)
    .usePlaintext()  // Use TLS in production
    .build();

CommandServiceGrpc.CommandServiceFutureStub commandService =
    CommandServiceGrpc.newFutureStub(channel);

Submitting Commands

Create a contract using the generated class:
License license = new License(
    providerParty,
    userParty,
    "Premium License",
    Instant.parse("2025-12-31T00:00:00Z")
);

// Submit as a create command via the Ledger API
Exercise a choice:
License.Renew renewArg = new License.Renew(
    Instant.parse("2026-12-31T00:00:00Z")
);

// Submit as an exercise command with the contract ID and choice argument

Processing Events

When reading transaction events from the Ledger API stream, use fromValue() to deserialize contract payloads:
CreatedEvent event = ...;
License license = License.fromValue(event.getArguments());

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:
sourceSets {
    main {
        java {
            srcDir("generated-java")
        }
    }
}
For Maven, add the generated directory as a source folder in your pom.xml:
<build>
  <plugins>
    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>build-helper-maven-plugin</artifactId>
      <executions>
        <execution>
          <id>add-source</id>
          <phase>generate-sources</phase>
          <goals><goal>add-source</goal></goals>
          <configuration>
            <sources>
              <source>generated-java</source>
            </sources>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>
You will also need the Daml Java bindings library as a dependency. Check the Canton 3.x documentation for the current Maven coordinates and version.

Reference Documentation

The full Javadoc for the Daml Java bindings library is available in the Canton 3.x SDK documentation. The generated classes follow the same patterns documented there.
This section was copied from existing reviewed documentation. Source: docs-website:docs/replicated/daml/3.4/sdk/component-howtos/application-development/daml-codegen-java.rst Reviewers: Skip this section. Remove markers after final approval.

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.yaml file.

Command line configuration

To view all available command line configuration options for Daml Codegen for Java, run dpm codegen-java --help in your terminal:
<DAR-file[=package-prefix]>...
                         DAR file to use as input of the codegen with an optional, but recommend, package prefix for the generated sources.
-o, --output-directory <value>
                         Output directory for the generated sources
-d, --decoderClass <value>
                         Fully Qualified Class Name of the optional Decoder utility
-V, --verbosity <value>  Verbosity between 0 (only show errors) and 4 (show all messages) -- defaults to 0
-r, --root <value>       Regular expression for fully-qualified names of templates to generate -- defaults to .*
--help                   This help text

Project file configuration

Specify the above settings in the codegen 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=2

References

Generated Java code

Daml primitives to Java types

Daml built-in types are translated to the following equivalent types in Java:
Daml typeJava typeJava Bindings Value type
Intjava.lang.LongInt64
Numericjava.math.BigDecimalNumeric
Textjava.lang.StringText
Booljava.util.BooleanBool
Partyjava.lang.StringParty
Datejava.time.LocalDateDate
Timejava.time.InstantTimestamp
List or []java.util.ListDamlList
TextMapjava.util.Map Restricted to using String keys.DamlTextMap
Optionaljava.util.OptionalDamlOptional
() (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
ContractIdFields 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
If any of these identifiers match one of the Java reserved keywords, the Daml Codegen appends a dollar sign $ 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.
module Foo.Bar.Baz where
package foo.bar.baz;
Records (a.k.a. product types)
A Daml record is represented by a Java class with fields that have the same name as the Daml record fields. A Daml field having the type of another record is represented as a field having the type of the generated class for that record.
-- Code from: ./code-snippets/Com/Acme/ProductTypes.daml
-- [Include actual code example here]
A Java file that defines the class for the type Person is generated:
package com.acme.producttypes;

public class Person extends DamlRecord<Person> {
  public final Name name;
  public final BigDecimal age;

  public static Person fromValue(Value value$) { /* ... */ }

  public Person(Name name, BigDecimal age) { /* ... */ }
  public DamlRecord toValue() { /* ... */ }
}
A Java file that defines the class for the type Name is generated:
package com.acme.producttypes;

public class Name extends DamlRecord<Name> {
  public final String firstName;
  public final String lastName;

  public static Person fromValue(Value value$) { /* ... */ }

  public Name(String firstName, String lastName) { /* ... */ }
  public DamlRecord toValue() { /* ... */ }
}
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 an ExerciseCommand for 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 type TemplateName.ContractId) and a field for the template data (of type TemplateName). With the static method TemplateName.Contract.fromCreatedEvent, you can deserialize a CreatedEvent to an instance of TemplateName.Contract.
— Code from: >
./code-snippets/Com/Acme/Templates.daml
— [Include actual code example here]

In particular, the codegen generates a file that defines six Java classes and one interface:

1.  `Bar`
2.  `Bar.ContractId`
3.  `Bar.Contract`
4.  `Bar.CreateAnd`
5.  `Bar.JsonDecoder$`
6.  `Bar.Exercises`

```java
package com.acme.templates;

public final class Bar extends Template {
  public static final Identifier TEMPLATE_ID = new Identifier("#some-package-name", "Templates", "Bar");
  public static final Identifier TEMPLATE_ID_WITH_PACKAGE_ID = new Identifier("some-package-id", "Templates", "Bar");
  public static final String PACKAGE_ID = "some-package-id";
  public static final String PACKAGE_NAME = "some-package-name";
  public static final PackageVersion PACKAGE_VERSION = new PackageVersion(new int[] {0, 0, 1});

  public static final Choice<Bar, Archive, Unit> CHOICE_Archive =
    Choice.create(/* ... */);

  public static final Choice<Bar, Bar_SomeChoice, Boolean> CHOICE_Bar_SomeChoice =
    Choice.create(/* ... */);

  public static final ContractCompanion.WithoutKey<Contract, ContractId, Bar> COMPANION =
    new ContractCompanion.WithoutKey<>(new ContractTypeCompanion.Package(Bar.PACKAGE_ID, Bar.PACKAGE_NAME, Bar.PACKAGE_VERSION),
      "com.acme.templates.Bar", TEMPLATE_ID, ContractId::new,
      v -> Bar.templateValueDecoder().decode(v), Bar::fromJson, Contract::new,
      List.of(CHOICE_Archive, CHOICE_Bar_SomeChoice));

  public final String owner;
  public final String name;

  public CreateAnd createAnd() { /* ... */ }

  public static class ContractId extends com.daml.ledger.javaapi.data.codegen.ContractId<Bar>
      implements Exercises<ExerciseCommand> {
    // inherited:
    public final String contractId;
  }

  public interface Exercises<Cmd> extends com.daml.ledger.javaapi.data.codegen.Exercises<Cmd> {
    default Cmd exerciseArchive(Unit arg) { /* ... */ }

    default Cmd exerciseBar_SomeChoice(Bar_SomeChoice arg) { /* ... */ }

    default Cmd exerciseBar_SomeChoice(String aName) { /* ... */ }
  }

  public static class Contract extends com.daml.ledger.javaapi.data.codegen.Contract<ContractId, Bar> {
    // inherited:
    public final ContractId id;
    public final Bar data;

    public static Contract fromCreatedEvent(CreatedEvent event) { /* ... */ }
  }

  public static final class CreateAnd
      extends com.daml.ledger.javaapi.data.codegen.CreateAnd
      implements Exercises<CreateAndExerciseCommand> { /* ... */ }

  public static class JsonDecoder$ { /* ... */ }
}
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.
-- Code from: ./code-snippets/Com/Acme/Variants.daml
-- [Include actual code example here]
The Java code generated for this variant is:
package com.acme.variants;

public class BookAttribute extends Variant<BookAttribute> {
  public static BookAttribute fromValue(Value value) { /* ... */ }

  public static BookAttribute fromValue(Value value) { /* ... */ }
  public abstract Variant toValue();
}
package com.acme.variants.bookattribute;

public class Pages extends BookAttribute {
  public final Long longValue;

  public static Pages fromValue(Value value) { /* ... */ }

  public Pages(Long longValue) { /* ... */ }
  public Variant toValue() { /* ... */ }
}
package com.acme.variants.bookattribute;

public class Authors extends BookAttribute {
  public final List<String> listValue;

  public static Authors fromValue(Value value) { /* ... */ }

  public Author(List<String> listValue) { /* ... */ }
  public Variant toValue() { /* ... */ }

}
package com.acme.variants.bookattribute;

public class Title extends BookAttribute {
  public final String stringValue;

  public static Title fromValue(Value value) { /* ... */ }

  public Title(String stringValue) { /* ... */ }
  public Variant toValue() { /* ... */ }
}
package com.acme.variants.bookattribute;

public class Published extends BookAttribute {
  public final Long year;
  public final String publisher;

  public static Published fromValue(Value value) { /* ... */ }

  public Published(Long year, String publisher) { /* ... */ }
  public Variant toValue() { /* ... */ }
}
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.
-- Code from: ./code-snippets/Com/Acme/Enum.daml
-- [Include actual code example here]
The Java code generated for this variant is:
package com.acme.enum;

public enum Color implements DamlEnum<Color> {
  RED,
  GREEN,
  BLUE;

  /* ... */
  public static final Color fromValue(Value value$) { /* ... */ }
  public final DamlEnum toValue() { /* ... */ }
}
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.
The Daml Codegen uses Java Generic types to represent Daml parameterized types. This Daml fragment defines the parameterized type Attribute, used by the BookAttribute type for modeling the characteristics of the book:
-- Code from: ./code-snippets/Com/Acme/ParameterizedTypes.daml
-- [Include actual code example here]
The Daml Codegen generates a Java file with a generic class for the Attribute a data type:
package com.acme.parameterizedtypes;

public class Attribute<a> {
  public final a value;

  public Attribute(a value) { /* ... */  }

  public DamlRecord toValue(Function<a, Value> toValuea) { /* ... */ }

  public static <a> Attribute<a> fromValue(Value value$, Function<Value, a> fromValuea) { /* ... */ }
}
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 the toValue 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.
Attribute<Long> pagesAttribute = new Attributes<>(42L);

Value serializedPages = pagesAttribute.toValue(Int64::new);
See Daml To Java Type Mapping for an overview of the Java Bindings Value types.
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 the toValue 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.
Attribute<Long> pagesAttribute = Attribute.<Long>fromValue(serializedPages,
    f -> f.asInt64().getOrElseThrow(() -> throw new IllegalArgumentException("Expected Int field").getValue());
See Java Bindings Value class for the methods to transform the Java Bindings types into corresponding Java types.
Non-exposed parameterized types
If the parameterized type is contained in a type where the actual type is specified (as in the BookAttributes type above), then the conversion methods of the enclosing type provides the required conversion function parameters automatically.
Convert optional values
The conversion of the Java Optional requires two steps. The Optional must be mapped in order to convert its contains before to be passed to DamlOptional::of function.
Attribute<Optional<Long>> idAttribute = new Attribute<List<Long>>(Optional.of(42));

val serializedId = DamlOptional.of(idAttribute.map(Int64::new));
To convert back DamlOptional to Java Optional, one must use the containers method toOptional. This method expects a function to convert back the value possibly contains in the container.
Attribute<Optional<Long>> idAttribute2 =
  serializedId.toOptional(v -> v.asInt64().orElseThrow(() -> new IllegalArgumentException("Expected Int64 element")));
Convert collection values
DamlCollectors provides collectors to converted Java collection containers such as List and Map to DamlValues in one pass. The builders for those collectors require functions to convert the element of the container.
Attribute<List<String>> authorsAttribute =
    new Attribute<List<String>>(Arrays.asList("Homer", "Ovid", "Vergil"));

Value serializedAuthors =
    authorsAttribute.toValue(f -> f.stream().collect(DamlCollector.toList(Text::new));
To convert back Daml containers to Java ones, one must use the containers methods toList or toMap. Those methods expect functions to convert back the container’s entries.
Attribute<List<String>> authorsAttribute2 =
    Attribute.<List<String>>fromValue(
        serializedAuthors,
        f0 -> f0.asList().orElseThrow(() -> new IllegalArgumentException("Expected DamlList field"))
             .toList(
                 f1 -> f1.asText().orElseThrow(() -> new IllegalArgumentException("Expected Text element"))
                      .getValue()
             )
    );
Daml interfaces
From this Daml definition:
-- Code from: ./code-snippets/Interfaces.daml
-- [Include actual code example here]
The generated file for the interface definition can be seen below. Effectively it is a class that contains only the inner type ContractId because one will always only be able to deal with Interfaces via their ContractId.
package interfaces

/* imports */

public final class TIf {
  public static final Identifier TEMPLATE_ID = new Identifier("94fb4fa48cef1ec7d474ff3d6883a00b2f337666c302ec5e2b87e986da5c27a3", "Interfaces", "TIf");

  public static final Choice<TIf, Transfer, ContractId> CHOICE_Transfer =
    Choice.create(/* ... */);

  public static final Choice<TIf, Archive, Unit> CHOICE_Archive =
    Choice.create(/* ... */);

  public static final INTERFACE INTERFACE = new INTERFACE();

  public static final class ContractId extends com.daml.ledger.javaapi.data.codegen.ContractId<TIf>
      implements Exercises<ExerciseCommand> {
    public ContractId(String contractId) { /* ... */ }
  }

  public interface Exercises<Cmd> extends com.daml.ledger.javaapi.data.codegen.Exercises<Cmd> {
    default Cmd exerciseUseless(Useless arg) { /* ... */ }

    default Cmd exerciseHam(Ham arg) { /* ... */ }
  }

  public static final class CreateAnd
      extends com.daml.ledger.javaapi.data.codegen.CreateAnd.ToInterface
      implements Exercises<CreateAndExerciseCommand> { /* ... */ }

  public static final class ByKey
      extends com.daml.ledger.javaapi.data.codegen.ByKey.ToInterface
      implements Exercises<ExerciseByKeyCommand> { /* ... */ }

  public static final class INTERFACE extends InterfaceCompanion<TIf> { /* ... */}
}
For templates the code generation will be slightly different if a template implements interfaces. To allow converting the ContractId of a template to an interface ContractId, an additional conversion method called toInterface is generated. An unsafeFromInterface is also generated to make the unchecked conversion in the other direction.
package interfaces

/* ... */

public final class Child extends Template {

  /* ... */

  public static final class ContractId extends com.daml.ledger.javaapi.data.codegen.ContractId<Child>
      implements Exercises<ExerciseCommand> {

    /* ... */

    public TIf.ContractId toInterface(TIf.INTERFACE interfaceCompanion) { /* ... */ }

    public static ContractId unsafeFromInterface(TIf.ContractId interfaceContractId) { /* ... */ }

  }

  public interface Exercises<Cmd> extends com.daml.ledger.javaapi.data.codegen.Exercises<Cmd> {
    default Cmd exerciseBar(Bar arg) { /* ... */ }

    default Cmd exerciseBar() { /* ... */ }
  }

  /* ... */

}