@AutoValue - “cannot find symbol class Generated”

2019-07-21 16:26发布

问题:

I am getting "cannot find symbol class Generated" while using the @AutoValue annotation.

public abstract  class Office{

public static Office create(String cityName, String companyName, String regionName) {
    return new AutoValue_Office(cityName, companyName, regionName);
}


public abstract String getCompanyName();
public abstract String getCityName();
public abstract String getRegionName();
}

Gradle dependency compile 'com.google.auto.value:auto-value:1.0-rc1'

Also, how can add only selected properties to equals and hashcode function.

回答1:

The problem is that you are using a version of Android that doesn't have the annotation javax.annotations.Generated (which was added in Java 6). You could add that manually as described in the answer to this question.

Concerning the question of excluding certain properties from equals and hashCode, there is currently no perfect way to do that. Often the desire to do this indicates a need to separate the properties that should be included into a separate class and use that in equals and hashCode. Alternatively, you could add non-final fields to the Office class and set them. For example, if regionName was not to be included, you could write something like this:

@AutoValue
public abstract class Office {
  private String regionName;

  public abstract String getCompanyName();
  public abstract String getCityName();
  public String getRegionName() {
    return regionName;
  }

  public static Office create(String cityName, String companyName, String regionName) {
    Office office = new AutoValue_Office(cityName, companyName);
    office.regionName = regionName;
    return office;
  }
}

The main disadvantage is that regionName is not final, so you don't get the same guarantees about access to it from other threads as you do for the other properties.