Search code examples
javasuperclassnashorn

java nashorn accessing superclass members


Im working with nashorn engine im trying to extend following java class

public abstract class AbstractClass {
    protected String name;
    protected long id;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public long getId() {
    return id;
}
public void setId(long id) {
    this.id = id;
}
public void init() {

}

Javascript code: In the method init() i want to access superclass members (directly set value of protected fields or use public setters)

var extended = Java.extend(AbstractClass.static , {
    init: function() {
        extended.name = "name"; //name is null
        setName("name") //exception <eval>:6 ReferenceError: "setName" is not defined
    }
});

In java i create object instance and call init method, but field "name" is null.

i've also tried to use Java.super(extended ).setName("name"); but this threw an exception <eval>:7 TypeError: Cannot call undefined

How can i access superclass members from javascript and nashorn?


Solution

  • Java.extend creates a subclass and not a subclass instance. But Java.super requires a subclass instance as an argument. So, the following script works:

    var extended = new (Java.extend(Java.type("AbstractClass"))) {
        init: function() {
            Java.super(extended).setName("foo");
        }
    };
    
    extended.init();
    print(extended.name);
    

    Somewhat larger example usage of Java.super is here

    https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-java_super