【问题标题】:Java builder pattern accessible from JavaScript in Rhino可从 Rhino 中的 JavaScript 访问的 Java 构建器模式
【发布时间】:2016-06-22 11:28:30
【问题描述】:

我想在 Rhino 中实现类似以下的功能(在 JavaScript 中)。

myService.http('http://localhost:9000')
         .path('foo/bar')
         .get();

然后让最终的 get() 返回实际响应。它以 Jersey 的 Java 网络请求构建器为蓝本。

我目前的Java代码是:

class MyHttpRequestBuilder {
    private final String baseUrl;
    private final StringBuilder path = new StringBuilder();
    private final Map<String, String> queryParams = new HashMap<>();
    private final Map<String, String> headers = new HashMap<>();

    public MyHttpRequestBuilder(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public MyHttpRequestBuilder path(String path) {
        this.path.append(path);
        return this;
    }

    public MyHttpRequestBuilder header(String headerKey, String headerValue) {
        headers.put(headerKey, headerValue);
        return this;
    }

    public MyHttpRequestBuilder queryParam(String queryKey, String queryValue) {
        queryParams.put(queryKey, queryValue);
        return this;
    }

    public String get() {
        return "Testing - Accessed " + baseUrl + " with path " + path;
    }
}

我已经在这样的服务类中注册了它:

public class MyService {
    public MyHttpRequestBuilder http(String baseUrl) {
        return new MyHttpRequestBuilder(baseUrl);
    }
}

然后,根据各种示例,我将其添加到 Rhino 上下文中的 Scriptable 容器中。

如果我只是直接调用简单地返回字符串或其他对象的函数,它很好

不幸的是,生成器方法是“return this;” (这将允许在 JS 端更流畅的代码)不想玩球。 Rhino甚至可以做到这一点吗?

我正在使用 Java 8 和 Rhino 1.7.7.1。

【问题讨论】:

  • 到底是什么问题? (另外,为什么是 Rhino 而不是 Nashorn?)

标签: javascript java builder rhino


【解决方案1】:

脚本引擎看不到您的构建器类型。公开:

public class MyHttpRequestBuilder {

【讨论】:

  • 忘记类上的公共访问修饰符真是太愚蠢了。它现在完美运行。谢谢!
猜你喜欢
  • 2010-10-17
  • 1970-01-01
  • 1970-01-01
  • 2013-05-10
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多