在Java和(Rhino)Javascript之间传递公共类型
我不清楚在使用(Mozilla)Rhino时如何在Javascript和Java之间转换类型的规则
文档中有一些关于String
的细节:
It's important to keep in mind that Java strings and JavaScript strings are not the same […]Rhino provides some help in reducing the differences between the two types. First, you can pass a JavaScript string to a Java method that requires a Java string and Rhino will perform the conversion. We actually saw this feature in action on the call to the java.lang.String constructor in the preceding example. Rhino also makes the JavaScript methods available to Java strings if the java.lang.String class doesn't already define them
但其他人呢?如果我将一个javascript数字传递给一个Java方法,该方法需要int
、double
(或Integer
或Double
),它会被转换吗?那long
/Long
呢?(哪个不适合Double
所以不适合JS编号
返回这些值的Java方法呢
然后是Boolean
/boolean
。JS常量true
和false
是否转换为适当的Java值?我见过这样的代码
java.lang.Boolean.TRUE.booleanValue()
来自JS,所以至少有些人认为不是
我已经看过Mozilla Rhino文档,但是如果我遗漏了一些明显的东西,一定要指出
# 1 楼答案
实际上,即使是“自动”转换,我也有一个问题,最终我转换了自己:
# 2 楼答案
在string没有实现js string拥有的所有插件的情况下(比如string.length!==string.length()),让包装器工厂为我做这项工作就解决了这个问题
这可以通过以下方式在顶层设置:
# 3 楼答案
下面是它如何将JavaScript类型转换为Java类型:http://www-archive.mozilla.org/js/liveconnect/lc3_method_overloading.html#InvocationConversion
试试看:
UPD
不幸的是,我也无法从Java类型映射中找到任何关于JavaScript的文档。但是tutorial显示JavaScript对象作为Java
Object
插入到上下文中并从上下文中检索,实际上可以是Double
、Boolean
、Function
(对于JavaScript函数;还实现了Scriptable
)或Scriptable
(对于对象)使用this code snippet可能会获得JavaScript Java类型映射引用:
https://gist.github.com/1089320#file_java_script_java_type_mapping.textile
至于LiveConnect兼容性。如果您指的是本脚注:
我认为这是关于使用Java的JavaScript不同于LiveConnect规范。从JavaScript使用Java应该是相同的