如何在Nashhorn JavaScript中扩展Java类并添加类成员变量

如何在Nashhorn JavaScript中扩展Java类并添加类成员变量

问题描述:

我尝试创建扩展Java类的类的实例,然后在该实例中添加一些类成员变量.这是我的尝试:

I try to create an instance of a class that extends a Java class, and in that instance add some class member variables. Here's my attempt:

var ui = Java.extend(javax.swing.JPanel, { 
    cb : new JCheckBox("A checkbox", true),
});

但是,Nashorn解释器会引发以下错误: "TypeError:函数 noSuchMethod (){[native code]}不是构造函数"

However, the Nashorn interpreter throws this error: "TypeError: function noSuchMethod() { [native code] } is not a constructor function"

我做错了什么?当我添加一个自定义类的实例(例如se.datadosen.util.Stopwatch)时,Nashorn并没有抱怨,但是当我尝试添加该JCheckBox时,它将引发此错误.

What am I doing wrong? Nashorn didn't complain when I added an instance of a custom class, like se.datadosen.util.Stopwatch, but it throws this error when I try to add that JCheckBox.

(我知道组件是通过.add()调用添加到面板中的,但是这个问题实际上是关于如何将类成员变量添加到子类中的.

(I know components are added to panels with the .add() call, but this question is really about how to add class member variables to a subclass.

Java.extend允许您将以JavaScript实现的方法添加到Java类中(实际上,是创建一个新类来对Java类进行子类化) Java类).至少根据文档,它不允许您添加任意属性.请参见 Nashorn Java API ,说:

Java.extend allows you to add methods implemented in JavaScript to a Java class (actually, to create a new class that subclasses the Java class). It does not allow you to add arbitrary properties, at least according to the documentation. See The Nashorn Java API, which says:

您可以使用Java.extend()函数扩展一个类,该函数将Java类型作为第一个参数,并将方法实现(以JavaScript函数的形式)作为其他参数."(强调)

You can extend a class using the Java.extend() function that takes a Java type as the first argument and method implementations (in the form of JavaScript functions) as the other arguments." (emphasis added)

您正在尝试添加对象作为类的属性,至少是当前编写代码的方式.

You are attempting to add an object as a property of the class, at least the way your code is presently written.