Search code examples
javascriptjava-8nashorn

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.

  • is this possible with a json like syntax?
  • i wouldnt have a problem using the Packages.Configuration / Java.type("Configuration"); Java.extend(), but have yet to have any success with that.
  • or would i have to make / use a proper reader for the returned value?

Solution

  • 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.