如何在Nashhorn JavaScript中扩展Java类并添加类成员变量 [英] How to extend Java class in Nashhorn JavaScript and add class member variables

查看:135
本文介绍了如何在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.

这篇关于如何在Nashhorn JavaScript中扩展Java类并添加类成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆