如何在Java Nashorn中声明类? [英] How to declare class in Java Nashorn?

查看:122
本文介绍了如何在Java Nashorn中声明类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以通过 Java.extend 扩展抽象类和接口,但是如何在类中添加自定义方法,构造函数和字段呢?我尝试过这样,但是它不起作用:

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
    }
});


推荐答案

正如A. Sundararajan正确指出的那样,向您的扩展类添加新功能。但为什么?

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

我怀疑这是因为Nashorn如何实现使用 Java.extend()创建的类。如果在脚本末尾添加语句 print(MyClass.class),您会看到类的类型为 jdk.nashorn.javaadapters。 java.lang.Object ,这是在Nashorn中定义的类,几乎不可能指定在定义扩展类时添加的自定义项。

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.

因此(大概)在运行时,Nashorn不会知道您添加的任何自定义设置(不包括覆盖)。 Nashorn文档暗含了此限制,但据我所知没有明确说明。请参阅相关的堆栈溢出问题以获取更多信息。

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.

这篇关于如何在Java Nashorn中声明类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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