AutoValue 是 Google 的一個開源庫,可以用來簡化 Java 開發(fā)中的一些繁瑣重復勞動,例如 getter/setter、toString()和 equals() 等方法。
如何使用AutoValue
AutoValue 的概念非常簡單:由你來寫一個抽象實體類,交給AutoValue來實現(xiàn)它。
創(chuàng)建抽象類
首先創(chuàng)建一個抽象類,為每個屬性添加一個get方法,加上 @AutoValue注解。其中,AutoValue_Animal 是根據(jù)AutoValue的命名格式AutoValue_類名來命名的,接下配置 IDE 來生成AutoValue_Animal。
import com.google.auto.value.AutoValue;
@AutoValue
abstract class Animal {
static Animal create(String name, int numberOfLegs) {
return new AutoValue_Animal(name, numberOfLegs);
}
//get方法
abstract String name();
abstract int numberOfLegs();
}
引入AutoValue
Maven
<dependency>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value-annotations</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value</artifactId>
<version>1.6.2</version>
<scope>provided</scope>
</dependency>
Gradle
dependencies {
compile "com.google.auto.value:auto-value-annotations:1.6.2"
annotationProcessor "com.google.auto.value:auto-value:1.6.2"
}
配置 IntelliJ IDEA
-
設(shè)置 Preferences -> Build, Execution, Deployment -> Compiler -> Annotation Processors
按照下圖進行設(shè)置:允許注解處理器
Annotation Processors 運行菜單欄 Build -> Build Project
-
找到所有 generated 目錄,右鍵菜單選擇 Mark Directory as -> Generated Sources Root
Generated Sources Root
測試 AutoValue
這時 Cannot resolve symbol 'AutoValue_Animal'的錯誤提示已經(jīng)消失,測試一下Animal類:
public void testAnimal() {
Animal dog = Animal.create("dog", 4);
assertEquals("dog", dog.name());
assertEquals(4, dog.numberOfLegs());
assertTrue(Animal.create("dog", 4).equals(dog));
assertFalse(Animal.create("cat", 4).equals(dog));
assertFalse(Animal.create("dog", 2).equals(dog));
assertEquals("Animal{name=dog, numberOfLegs=4}", dog.toString());
}

