从 rhino javascript 调用静态 Java 方法

发布于 2025-01-01 03:48:04 字数 906 浏览 5 评论 0原文

我有静态java方法,我用这个方法添加到javascript中:

public void addJavaMethod(Method method)
{
    try
    {
            FunctionObject fo = new FunctionObject(method.getName(), method, m_scope);
            FunctionObject.putProperty(m_scope, method.getName(), fo);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

我总是在这些方法中使用对象类作为参数,因为否则会出现错误,例如:

而不是

static void setSomeFloatValueHere(float value){}

我使用:

static void setSomeFloatValueHere(Object value)
{//convert this object to a float}

使用布尔值,我可以直接转换:

static void setBoolean(Object b){someBooleanObject = (Boolean)b;}

但对于 int、float、long、double 等,我无法做到这一点。 我收到错误:

org.mozilla.javascript.Undefined cannot be cast to java.lang.Integer

如何才能使其也适用于这些类型?可能还有其他非原始类型对象? 谢谢

I have static java methods which I add to javascript with this method:

public void addJavaMethod(Method method)
{
    try
    {
            FunctionObject fo = new FunctionObject(method.getName(), method, m_scope);
            FunctionObject.putProperty(m_scope, method.getName(), fo);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

I always use the object class for parameters in these methods because it otherwise comes up with errors, for example:

instead of

static void setSomeFloatValueHere(float value){}

I use:

static void setSomeFloatValueHere(Object value)
{//convert this object to a float}

With booleans I can do a direct cast:

static void setBoolean(Object b){someBooleanObject = (Boolean)b;}

But with int,float,long,double, etc, I cannot do this.
I receive an error:

org.mozilla.javascript.Undefined cannot be cast to java.lang.Integer

How can I get this to work with those types as well? and possibly other non primitive type objects?
Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

唔猫 2025-01-08 03:48:04

您的对象可能不是 Integer,而是具有 intValue()Number

您可以使用 value.getClass().getName() 检查实际类型。

Your object is probably not an Integer, but rather Number which has an intValue()

You can check the actual type by using value.getClass().getName().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文