aepurniet
aepurniet

Reputation: 1727

instantiate class in via nashorn

im thinking about replacing all my xml files and builders that i use for configuration with javascript / nashorn. lets say i have a java class that is builder style configuration object

class Configuration {
    String name;
    Configuration withName(String name) {
        this.name = name;
        return this;
    }
    int number;
    Configuration withNumber(int number) {
        this.number = number;
        return this;
    }
}

i would like to instantiate this class directly in javascript and have nashorn return to me an instance of it. i would like to code it in javascript like

{
    name: 'qwerty',
    number: 42
};

and then finally read the file, pass it into the script engine, and have it evaluate the object as an instance of Configuration.

Upvotes: 0

Views: 443

Answers (2)

Brent Larsen
Brent Larsen

Reputation: 1072

You could cheat a little by attaching a converter function to your configuration type. This could be added easily on the JS side rather than trying to make it in Java.

var ConfigClass = Java.type('Configuration');

ConfigClass.fromJsObj = function(jsObj) {
    var newConfig = new ConfigClass();
    foreach(var prop in jsObj) {
        newConfig[prop] = jsObj[prop];
    }
    return newConfig;
}

var myConfig = ConfigClass.fromJsObj( { name: "qwerty", number: 42 } );

Upvotes: 1

Andrey Chaschev
Andrey Chaschev

Reputation: 16496

No, Nashorn won't support this from what I've seen from available docs and JSR-223. You might need to use i.e. Jackson's ObjectMapper to deserialize JSON. And this should not be a problem, because Nashorn allows you to do almost anything in JavaScript: A JavaFX Script Application Examples.

You might also want to consider Groovy which has it's own map syntax which can be used inside constructors: Groovy Goodness: Using Lists and Maps As Constructors. Groovy is often used to define configuration.

Upvotes: 1

Related Questions