How to declare class in Java Nashorn?

2019-07-23 04:37发布

问题:

I know that i can extend abstract classes and interfaces through Java.extend, but how can i add custom methods, constructors and fields in class? I tried to like this, but it's not works:

var MyClass = Java.extend(java.lang.Object, {
    myField1: java.lang.String,
    myField2: java.lang.Object,
    "<init>": function(arg1, arg2) {
        // Try to declare constructor
    },
    myMethod: function(arg1, arg2, arg3) {
        // Try to declare method
    }
});

回答1:

As A. Sundararajan correctly states, you can't add new features to your extended class. But why?

I suspect it's because of how Nashorn implements classes created using Java.extend(). If you add the statement print(MyClass.class) at the end of your script you can see that the type of your class is "jdk.nashorn.javaadapters.java.lang.Object", a class which is defined within Nashorn, and is very unlikely to specify the same customization you added when defining your extended class.

So (presumably) at run time any customization you added, excluding overriding, won't be known to Nashorn. The Nashorn documentation implies this limitation, but does not explicitly spell it out as far as I know. See this related Stack Overflow question for more information.



回答2:

You cannot add a new method to subclass. You cannot define new constructor (more like anonymous class usage in Java code). You can only override super class method (or implement super interface methods).