简体   繁体   中英

Can't chain method calls for builder pattern with compiled inner class

I am creating an android application that uses an aar file that has a class that uses the builder pattern. However, I suspect this is a plain old Java issue.

Everything works fine if I don't use any of the chained setter methods:

ProjectConfig config = new ProjectConfig$Builder("reqparam0")
                       .build() // this works fine

However, once I try to use any of chained setter methods,

ProjectConfig config = new ProjectConfig$Builder("reqParam0")
                      .contactEmail("optParam0")
                      .build() // ERROR - can't find build() method

I know that there is no problem with the Builder implementation itself, as I built it and it works just fine when it is used without first being compiled and packaged into another application as an aar file.

Note that I need to use the '$' accessor instead of the normal '.' becuase it is an already compiled class. I suspect this has something to do with the issue as well.

Here is the class:

public class ProjectConfig {
  private final String apiKey;
  private final boolean batterySavingMode;
  private final String contactEmail;

  public ProjectConfig(Builder builder) {
    apiKey = builder.apiKey;
    batterySavingMode = builder.batterySavingMode;
    contactEmail = builder.contactEmail;
  }

  public String getApiKey() {
    return apiKey;
  }

  public boolean isBatterySavingMode() {
    return batterySavingMode;
  }

  public String getContactEmail() {
    return contactEmail;
  }

  public static class Builder{
    // Required parameters
    private String apiKey;

    // Optional parameters
    private boolean batterySavingMode = false;
    private String contactEmail = null;

    public Builder(String apiKey){
      this.apiKey = apiKey;
    }

    public Builder batterySavingMode(boolean enabled){
      this.batterySavingMode = enabled;
      return this;
    }

    public Builder contactEmail(String contactEmail) {
      this.contactEmail = contactEmail;
      return this;
    }

    public ProjectConfig build(){
      return new ProjectConfig(this);
    }
 }

}

Can anyone shed some light on what may be causing the problem?

This is actually a compile-time error. The methods the IDE can't find turn red, and says "cannot resolve method."

However, it appears to be an error with the IDE... at least the method is found at runtime, because I tested it and everything goes smoothly when the application runs.

I even checked the debugger, and a ProjectConfig object is created with the correct values, even for the method it says it cannot resolve.

So it seems like this would be better off as a bug report to JetBrains...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM