如何解决Java构造函数使用参数创建新列表
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无法从静态内容中引用。
我想知道那是什么意思。 我是否正确构建了构造函数? 我想我不是。我只希望能够传入一个String,以便构造函数可以使用该String创建一个String列表。
解决方法
您的班级访问修饰符设置为私有。尝试将访问修饰符设置为public。
public class BertJsonRequest {
private Integer id;
private List<String> texts = new ArrayList<>();
public BertJsonRequest(int x,String text) {
id = x;
texts.add(text);
}
}
,
我猜您的BertJsonRequest
是BertClient
的内部类。您无法在BertJsonRequest
之外实例化BertClient
。您可以将BertJsonRequest
类设置为静态,以使其正常工作。
通过阅读您对他人答案的评论,我了解到,您的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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。