how to access methods from my class inside javascript in Nashorn

后端 未结 1 1941
名媛妹妹
名媛妹妹 2021-01-24 23:06

In Nashorn it is possible to access predefined classes of java ,

 var ArrayList = Java.type(\'java.util.ArrayList\');
 var list = new ArrayList();
 list.add(\'a         


        
相关标签:
1条回答
  • 2021-01-24 23:45

    You must use the -classpath option of jrunscript or jjs.

    -cp, -classpath (-cp path. Specify where to find user class files.)

    The Java class:

    package de.lhorn.so;
    
    public class Foo {
    
        public final static int ZERO = 0;
    
        public static int i() {
            return 1;
        }
    }
    

    Compile it:

    $ javac de/lhorn/so/Foo.java
    $ tree de 
    de
    └── lhorn
        └── so
            ├── Foo.class
            └── Foo.java
    

    Use it:

    % jrunscript -cp .
    nashorn> var Foo = Java.type("de.lhorn.so.Foo")
    nashorn> Foo.ZERO
    0
    nashorn> Foo.i
    [jdk.internal.dynalink.beans.SimpleDynamicMethod int de.lhorn.so.Foo.i()]
    nashorn> Foo.i()
    1
    
    0 讨论(0)
提交回复
热议问题