java构造函数使用参数创建新列表

of1yzvn4  于 2021-07-09  发布在  Java
关注(0)|答案(3)|浏览(383)

java新手。我正在尝试创建一个类来转换为json字符串,并使用gson作为post请求发送。此类是在名为 BertClient :

private class BertJsonRequest {
    private Integer id;
    private List<String> texts;

    public BertJsonRequest(int x, String text) {
        this.id = x;
        this.texts = new ArrayList<>();
        this.texts.add(text);
    }
}

我如何使用它:

BertJsonRequest rawRequestBody = new BertJsonRequest(1, text);
 Gson gsonToJson = new Gson();
 String requestBody = gsonToJson.toJson(rawRequestBody);

对于我正在创建的行 new BertJsonRequest 我的ide告诉我bertclient.this不能从静态内容引用。
我想知道那是什么意思。我是否正确构建构造函数?我想我不是。我只希望能够传入一个字符串,以便构造函数可以使用该字符串创建一个字符串列表。

0pizxfdo

0pizxfdo1#

通过阅读你对别人答案的评论,我的理解是 BertClientRequest 可能是一个内部类。
如果它确实是一个内部类,并且您尝试在包含类的静态方法中调用它,那么很明显您不能示例化内部类,因为内部类不是 static .

public class BertClient {
  private class BertClientRequest {
    /* some code */
  }

  static void aStaticMethod() {
    // ...
    // Inner class BertClientRequest is unknown to your static method as it is not static,
    // thus giving you a compile time error
    BertClientRequest rawRequest = new BertClientRequest(1, text);
    // ...
  }
}

在这种情况下,解决方法是将内部类更改为 static : private static class BertClientRequest

iezvtpos

iezvtpos2#

您的类访问修饰符设置为private。尝试将访问修饰符改为public。

public class BertJsonRequest {
    private Integer id;
    private List<String> texts = new ArrayList<>();

    public BertJsonRequest(int x, String text) {
        id = x;
        texts.add(text);
    }
}
5jvtdoz2

5jvtdoz23#

我猜你的 BertJsonRequest 是一个 BertClient . 不能示例化 BertJsonRequest 外部 BertClient . 你可以让 BertJsonRequest 类static以使其工作。

相关问题