Just try to use Google AutoValue on one of my existing open source project, the steps are basically as below.
Before Apply: A simple UserBean
with GitHubService
.
public interface GitHubService {
String BASE_URL = "https://api.github.com/";
@GET("users")
Observable<List<UserBean>> getUserList();
}public class RetrofitHelper {
public GitHubService newGitHubService() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(GitHubService.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
return retrofit.create(GitHubService.class);
}
}public class UserBean {
public String login;
public int id;
public String avatarUrl;
}
After Apply: It need to provide two libraries AutoValue & AutoValueGson, and the UserBean
with @AutoValue
annotation.
dependencies {
annotationProcessor "com.google.auto.value:auto-value:1.2"
annotationProcessor "com.ryanharter.auto.value:auto-value-gson:0.4.5"
provided "com.google.auto.value:auto-value:1.2"
provided "com.ryanharter.auto.value:auto-value-gson:0.4.5"
}public interface GitHubService {
String BASE_URL = "https://api.github.com/";
@GET("users")
Observable<List<UserBean>> getUserList();
}@GsonTypeAdapterFactory
public abstract class RetrofitGsonTypeAdapterFactory implements TypeAdapterFactory {
public static TypeAdapterFactory create() {
return new AutoValueGson_RetrofitGsonTypeAdapterFactory();
}
}public class RetrofitHelper {
public GitHubService newGitHubService() {
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(RetrofitGsonTypeAdapterFactory.create())
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(GitHubService.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
return retrofit.create(GitHubService.class);
}
}@AutoValue
public abstract class UserBean {
public abstract String login();
public abstract int id();
@Nullable
public abstract String avatarUrl();
public static UserBean create(String login, int id, @Nullable String avatarUrl) {
return new AutoValue_UserBean(login, id, avatarUrl);
}
public static TypeAdapter<UserBean> typeAdapter(Gson gson) {
return new AutoValue_UserBean.GsonTypeAdapter(gson);
}
}
The full project can be found at GitHub.