Contact Us 1-800-596-4880

Reusing Types from Java Classes

Use the import directive with the java! prefix when loading a Java class. The prefix java! tells DataWeave to use the Java module loader. After the module loads, you can call constructors, variables, and functions (see Call Java Methods with DataWeave). The class type is also available. DataWeave exposes the type of the Java class with the type name Class.

Java classes are mapped to the DataWeave types listed in Java Value Mapping. If a Java class is not specified in the table, DataWeave treats the class as JavaBean and maps it to a DataWeave Object type. The keys in that object match the names of the properties in the Java class and their values correspond to the DataWeave type that matches the property class. The following example shows how DataWeave takes all properties from the Java getters:

Product Class:

package org.mycompany;


public class Product {
    private String name;
    private int price;

    public Product(String name, int price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public int getPrice() {return price;}
    public void setPrice(int price) {this.price = price;}
}

Loading the type for this Java class has the same effect as declaring this DataWeave type:

type Class = { name?: String | Null, price?: Number | Null }

The following example uses the type Product::Class as any other type in DataWeave. Creating a DataWeave object by calling the function Product::new (which calls the constructor of the Java class) also matches the type Product::Class. Notice that the import directive lacks from and instead uses the type Class prefix Product::. The prefix enables more declarative use of the type and avoids collisions with any other imported Class types:

DataWeave Script:
%dw 2.0
output json
import java!org::mycompany::Product

var aBook: Product::Class = {name: "Learn DW", price: 123}
fun description(p: Product::Class) = "The product: $(p.name), costs: $(p.price)"

type Order = {
    product: Product::Class,
    date: LocalDateTime
}
---
{
    a: Product::new("DW lang", 321) is Product::Class,
    b: description(aBook),
    c: {product: aBook, date: |2022-12-18T14:00:00|} is Order
}
Output:
{
    a: true,
    b: "The product: Learn DW, costs: 123",
    c: true
}