Sidebar

How can I Implement a Java Interface in a Rhino Script?

0 votes
837 views
asked Apr 30, 2018 by brandon-w-8204 (33,820 points)

1 Answer

0 votes

Given the following Java interface:

public interface BooleanSupplier {
     boolean getAsBoolean();
}

In Java, you can provide an anonymous implementation of this interface as follows:

final BooleanSupplier supplier = new BooleanSupplier() {
    @Override
    public boolean getAsBoolean() {
        return false;
    }
};

This same thing can be accomplished in Rhino with the following code:

var obj = { 
    getAsBoolean: function () { 
        return false;
    } 
}

You can then pass this implementation as a parameter.  In this case, we are passing it to Configuration:

// Configuration takes a BooleanSupplier interface implementation
var config = new Configuration(supplier)

For further information, please see:
https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Scripting_Java#The_JavaAdapter_Constructor

 

answered Apr 30, 2018 by brandon-w-8204 (33,820 points)
edited Apr 30, 2018 by brandon-w-8204
...