Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
How to copy/transform an AutoValue object with builder

I'm playing auto-value with builder recently. And I'm in such a situation, say I have to transform an existing object to a new one with a few properties get updated. The example code is here:

@AutoValue
public abstract class SomeObject {
    public static Builder builder() {
      ...
    }

    public abstract String prop1();
    public abstract int prop2();

    // Populate a builder using the current instance.        
    public Builder newBuilder() {
        ...
    }
}

Notice I wrote a newBuilder method, so that I can do the transformation like this:

SomeObject resultedObject = originObject.newBuilder()
    .setProp2(99)
    .build();

Yes, I can write the newBuilder like this:

public Builder newBuilder() {
    return new AutoValue_SomeObject.Builder()
            .setProp1(this.prop1())
            .setProp2(this.prop2());
}

But there should be a better way, especially when dealing with complex objects in real life. Something like this is way better:

public Builder newBuilder() {
    return new AutoValue_SomeObject.Builder(this);
}

Unfortunately, the generated constructor Builder(SomeObject) is private, and I cannot find any reference to it.

So what's your thoughts about the problem?

The AutoValue version is 1.4-rc2. Thanks in advance.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Please refer to JakeWharton's reply

The answer is to declare a toBuilder method in SomeObject

public abstract Builder toBuilder();

the generated sub-class will implement this method.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda