How to subclass an inner (static) class in Rhino?

你说的曾经没有我的故事 提交于 2019-12-11 05:55:16

问题


I'm trying to subclass an inner class (defined in Java) in Rhino, and I can't seem to make it work.

I've got some compiled Java code (which I essentially can't change) that has an inner abstract class:

package mypackage;
class MyClass {
  abstract static class MyInnerClass {
    abstract void print(String s);
  }
}

From Rhino, I can see it just fine:

js> Packages.mypackage.MyClass.MyInnerClass
[JavaClass mypackage.MyClass$MyInnerClass]

But I can't figure out how to subclass it. I figured something like this would work, since I do it for non-inner classes:

var a = new JavaAdapter(Packages.mypackage.MyClass.MyInnerClass, {
  print: function(s) { print("s=" + s); },
});

Not only does it not work, Rhino itself quits, and gives me quite the stack trace:

Exception in thread "main" java.lang.IllegalAccessError: class adapter1 cannot access its superclass mypackage.MyClass$MyInnerClass
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:676)
at org.mozilla.javascript.DefiningClassLoader.defineClass(DefiningClassLoader.java:62)
    ...

Am I doing it wrong? Any ideas?

EDIT: Oh, I just realized that MyClass isn't declared "public". Could that be it?


回答1:


The inner class must be public.

package org.example;

public class Foo
{
    public abstract static class MyInnerClass
    {
        abstract void print(String s);
    }

    public void pr()
    {
        System.out.println("foo");
    }
}

First test: Subclass and instantiate the outer Foo class:

$ java -classpath $PWD:/usr/share/java/js.jar:/usr/share/java/jline.jar:. org.mozilla.javascript.tools.shell.Main
Rhino 1.7 release 2 2010 01 20
js> var a = new JavaAdapter(Packages.org.example.Foo, {
  >   pr: function() { print("jsfoo"); },
  > });
js> a.pr();
jsfoo

Second test: Subclass and instantiate the inner class:

js> var b = new JavaAdapter(Packages.org.example.Foo.MyInnerClass, {
  >   print: function(s) { print("Inner: " + s); },
  > });
js> b.print("one");
Inner: one
undefined

Note: If I change the inner class not to be public, I get the exact same error you reported.




回答2:


Since it's visibility is package private you may only create sub class of it in same package, maybe that's the problem?



来源:https://stackoverflow.com/questions/4572803/how-to-subclass-an-inner-static-class-in-rhino

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!