为什么 Javascript(在 Rhino 中运行)无法访问 java.lang.reflect.Method 实例上的方法?
下面是我所看到的一个非常简单的示例:
jrunscript -f -
js> var d = new java.util.Date();
js> var m = d.getClass().getMethods();
js> println(m[0].getClass().getName());
java.lang.reflect.Method
js> var name = m[0].getName();
script error: sun.org.mozilla.javascript.internal.WrappedException: Wrapped java.lang.UnsupportedOperationException: invocation not supported (<STDIN>#1) in <STDIN> at line number 1
js> var time = d.getTime();
js> println(time);
1278421741768
js>
变量“d”是一个 Java“Date”实例,“m”是“Date”类的 Java“Method”对象数组。然而,当我尝试在“Method”实例之一上调用 getName()
时,它不起作用。请注意,在“Date”实例上调用 getTime()
效果很好,几乎所有其他对 Java 对象的调用也是如此。 (当然,我还没有进行详尽的探索,但它通常是有效的,这就是为什么“方法”看起来很奇怪。)
如果我(在 Java 端)编写一个基本上包装“方法”和委托的类,那么它就可以工作美好的。因此,Javascript 领域和“方法”提供的内容之间并不存在某种内在的障碍。 (事实上,我认为脚本层本身首先必须进行反射才能提供基本设施。)
我记得上次我通过 JDK 6 脚本框架使用 Rhino 时遇到过并解决了这个问题。我不记得我是否弄清楚了为什么会发生这种情况。有人知道吗?
Here's a very simple example of what I see:
jrunscript -f -
js> var d = new java.util.Date();
js> var m = d.getClass().getMethods();
js> println(m[0].getClass().getName());
java.lang.reflect.Method
js> var name = m[0].getName();
script error: sun.org.mozilla.javascript.internal.WrappedException: Wrapped java.lang.UnsupportedOperationException: invocation not supported (<STDIN>#1) in <STDIN> at line number 1
js> var time = d.getTime();
js> println(time);
1278421741768
js>
The variable "d" is a Java "Date" instance, and "m" is the array of Java "Method" objects for the "Date" class. When I try to call getName()
on one of the "Method" instances, however, it doesn't work. Note that calling getTime()
on the "Date" instance works fine, as do pretty much all other calls to Java objects. (Well, I haven't run an exhaustive exploration of course, but it generally works and that's why "Method" seems weird.)
If I write (on the Java side) a class that basically wraps "Method" and delegates, that works fine. So it's not like there's some intrinsic barrier between the Javascript domain and the stuff that "Method" supplies. (Indeed, I imagine that the script layer itself has to do reflection to provide the basic facility in the first place.)
I recall having encountered and hacked around this problem the last time I was fooling around with Rhino via the JDK 6 script framework. I don't recall whether I figured out why it happens or not. Does anybody know?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
IIRC,这是因为许多方法使用直接调用者进行某些安全检查。如果您使用
Method.invoke
调用这些方法,则invoke
的调用者将被视为直接调用者。这些方法列在当前 Java 安全编码指南 的第 6 节中。IIRC, it's because a number of methods use the immediate caller for certain security checks. If you use
Method.invoke
to call these methods, then the caller ofinvoke
is taken as the immediate caller. These methods are listed in section 6 of the current Java Secure Coding Guidelines.