Lykosz
Lykosz

Reputation: 87

Java constructor use parameter to create new list

New to Java. I'm trying to create a class to convert to JSON string to send as POST request using GSON. This class was created within a public class Called 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);
    }
}

How I use that:

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

For the line where I'm creating new BertJsonRequest My IDE tells me that BertClient.this cannot be referenced from a static content.

I wonder what that means. Am I building the constructor correctly? I think I'm not. I just want to be able to pass in a String so that constructor can create a List of String using that String.

Upvotes: 0

Views: 79

Answers (3)

Oskar Grosser
Oskar Grosser

Reputation: 3434

What I understood by reading your comments on other's answers was, that your BertClientRequest probably is an inner class.
In case it really is an inner class, and you try to call it in a static method of your containing class, it becomes apparent that you cannot instantiate your inner class as that inner class is not 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);
    // ...
  }
}

The fix would be in this case to change your inner class to static:
private static class BertClientRequest

Upvotes: 0

Dakshinamurthy Karra
Dakshinamurthy Karra

Reputation: 5463

I guess your BertJsonRequest is a inner class of BertClient. You can't instantiate BertJsonRequest outside of BertClient. You can make BertJsonRequest class static for this to work.

Upvotes: 0

Shawn Lim
Shawn Lim

Reputation: 281

Your class access modifier is set to private. Try setting the access modifier to public instead.

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

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

Upvotes: 1

Related Questions