简体   繁体   中英

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

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?

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.

因为它的可见性是包私有的,所以您只能在同一包中创建它的子类,也许是问题所在吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM