当`ScriptEngine`的case对象时,`ClassCastException`

时间:2016-07-17 15:03:38

标签: java groovy scriptengine

我尝试用ScriptEngine在Java和Groovy之间传递对象,这样我就可以将一些逻辑分解为groovy脚本。但我遇到了两个问题:

  1. 无法将对象传递给groovy脚本。
  2. 无法从groovy脚本中获取对象。
  3. 以下是代码:

    App.java

    package test.testScriptEngine;
    
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    
    import javax.script.Bindings;
    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    
    
    public class App {
        public static void main(String[] args) throws Exception {
            App app=new App();
            Output out=app.runSript();
            System.out.println(out.a);
        }
    
        public Output runSript() throws ScriptException, FileNotFoundException {
    
            ScriptEngineManager sem = new ScriptEngineManager();
            ScriptEngine engine = sem.getEngineByName("groovy");
            Bindings binding = engine.createBindings();
    
            Input input=new Input(4,5);
            binding.put("input", input);
    
            FileReader reader = new FileReader("src/main/resources/test.groovy");
            Object obj = engine.eval(reader, binding);
    
            return (Output) obj;
        }
    
    }
    class Input{
        public Input(int i, int j) {
            this.a=i;
            this.b=j;
        }
        int a=1;
        int b=2;
    }
    class Output{
        int a=1;
    }
    

    test.groovy

    package test.testScriptEngine;
    
    class Input{
            int a=1;
            int b=2;
        Input(int a,int b){
            this.a=a;
            this.b=b;
        }
    }
    class Output{
            int a=1;
    }
    
    Output cal(Input input){
        Output out= new Output();
        out.a=input.a+input.b;
        println(out.a);
        return out;
    }
    Input input=new Input(2,3);
    return cal(input);
    

    输出是:

    5
    Exception in thread "main" java.lang.ClassCastException: test.testScriptEngine.Output cannot be cast to test.testScriptEngine.Output
        at test.testScriptEngine.App.runSript(App.java:31)
        at test.testScriptEngine.App.main(App.java:15)
    

    预期输出应为9,并且应返回Output

1 个答案:

答案 0 :(得分:1)

当Groovy类加载器编译脚本时,它会创建类test.testScriptEngine.Output

但是,从脚本生成的类与从Java代码编译的test.testScriptEngine.Output类不同。即使它们的字节码相等,不同的类加载器也会使它们成为不同的类。