gpt4 book ai didi

java - Rhino API - 使用 org.mozilla.javascript.Context 访问 js 方法?

转载 作者:行者123 更新时间:2023-12-01 14:09:33 35 4
gpt4 key购买 nike

我如何访问此脚本中的 get 方法:

(function( global ){

var Result;

(Result = function( val ) {
this.tpl = val || '' ;
}).prototype = {

get: function ()
{
return 'text' ;
}

};

global.Result = Result ;

} ( window ) ) ;

我尝试过这样的方式:

创建Window类和Result接口(interface):

public interface Result{ public String get(); }

public class Window { public Result Result; }

调用js函数:

public void call() {

Context context = Context.enter();

ScriptableObject scope = context.initStandardObjects();

FileReader fileReader = new FileReader("file.js");

Object window = Context.javaToJS(new Window(), scope);

scope.put("window", scope, window);

context.evaluateReader(scope, fileReader, "test", 1, null);

context.evaluateString(scope, "Result = window.Result;", "test", 2, null);

context.evaluateString(scope, "result = Result.get();", "test", 3, null);
Object result = scope.get("result", scope);
System.out.println("\n" + Context.toString(result));
context.exit();

}

但我无法从 get 函数获取返回结果:

最佳答案

它对我有用:

public class Result extends ScriptableObject{

@Override
public String getClassName() {
// TODO Auto-generated method stub
return "Result";
}
}

public class Window extends ScriptableObject {
private Result Result;

public Result getResult() {
return Result;
}

@Override
public String getClassName() {
return "Window";
}
}

public void call() {

Context context = Context.enter();

ScriptableObject scope = context.initStandardObjects();

FileReader fileReader = new FileReader("file.js");

Window window = new Window();

scope.put("window", scope, window);

scope.put("window.Result", window.getResult());

context.evaluateReader(scope, fileReader, "test", 1, null);

context.evaluateString(scope, "Result = window.Result;", "test", 1, null);

context.evaluateString(scope, "var myResult = new Result();", "test", 1, null);

context.evaluateString(scope, "r = myResult.get();", "test", 1, null);
Object result = scope.get("r", scope);
System.out.println("\n" + Context.toString(result));
context.exit();

}

关于java - Rhino API - 使用 org.mozilla.javascript.Context 访问 js 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18630833/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com