Skip to content

targetTypeMapping not working when executing a Java lambda #899

@polsotos-picnic

Description

@polsotos-picnic

Hi,

Is there an explanation why the first unit test works and the second one doesn't?
I would expect the mapping to be applied in both cases.

import java.util.function.Consumer;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.HostAccess;
import org.junit.jupiter.api.Test;

public class TargetTypeMappingTest {

    @Test
    void testTargetTypeMappingWhenObject() {
        HostAccess hostAccess = HostAccess.newBuilder(HostAccess.ALL)
                .targetTypeMapping(
                        Integer.class, // Source type: Integer
                        String.class, // Target type: String
                        null, // Accept all
                        Object::toString // Converter function
                )
                .build();

        try (Context context = Context.newBuilder().
                allowAllAccess(true)
                .allowHostAccess(hostAccess).build()) {

            context.getBindings("js").putMember("object", new IntegerToString());
            context.eval("js", "object.print(2)"); // works!
        }
    }

    @Test
    void testTargetTypeMappingWhenFunction() {
        HostAccess hostAccess = HostAccess.newBuilder(HostAccess.ALL)
                .targetTypeMapping(
                        Integer.class, // Source type: Integer
                        String.class, // Target type: String
                        null, // Accept all
                        Object::toString // Converter function
                )
                .build();

        try (Context context = Context.newBuilder().
                allowAllAccess(true)
                .allowHostAccess(hostAccess).build()) {

            Consumer<String> function = System.out::println;
            context.getBindings("js").putMember("javaFunction", function);
            context.eval("js", "javaFunction(2)"); // ClassCast exception
        }
    }

    public static class IntegerToString {
        public void print(String stringValue) {
            System.out.println(stringValue);
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions