我建立了一个测试项目,看看我如何将 RoboGuice 和 Proguard 与注入的参数化构造函数一起使用。
这是我的 proguard-rules.pro 文件:
-keep class roboguice.** { *; }
-keep interface roboguice.** { *; }
-dontwarn roboguice.**
-keep class org.roboguice.** { *; }
-keep interface org.roboguice.** { *; }
-dontwarn org.roboguice.**
-keepattributes **
-keep class com.example.vladfatu.roboguicetest.application.TestModule
-keep class com.google.inject.Binder
-keep class com.google.inject.Module
-keep public class com.google.inject.** { *; }
# keeps all fields and Constructors with @Inject
-keepclassmembers,allowobfuscation class * {
@com.google.inject.Inject <fields>;
@com.google.inject.Inject <init>(...);
}
这是我的测试模块:
public class TestModule implements Module {
public TestModule() {
super();
}
@Override
public void configure(Binder binder) {
binder.bind(StateProvider.class).to(RoboTestStateProvider.class);
}
}
这是 StateProvider :
public interface StateProvider {
String getState();
}
这是 RoboTestStateProvider :
public class RoboTestStateProvider implements StateProvider {
private Context context;
@Inject
public RoboTestStateProvider(Context context) {
this.context = context;
}
@Override
public String getState() {
return "State";
}
}
这是应用程序类:
public class RoboTestApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
RoboGuice.setUseAnnotationDatabases(false);
configureInjection();
}
protected void configureInjection() {
RoboGuice.getOrCreateBaseApplicationInjector(this, RoboGuice.DEFAULT_STAGE, RoboGuice.newDefaultRoboModule(this), new TestModule());
}
}
当它尝试创建 Application Injector(在 Application 类中)时,它会失败并出现以下错误:
在 com.example.vladfatu.roboguicetest.monitor.RoboTestStateProvider 中找不到合适的构造函数。类必须有一个(并且只有一个)用@Inject 注释的构造函数或一个非私有的零参数构造函数。
我以为“@com.google.inject.Inject (...);” proguard 规则中的行应该已经解决了这个问题,但它没有。我什至尝试反编译 apk 以确保 @Inject 注释存在(在构造函数之前)并且它存在,但它仍然不起作用。
显然,没有 Proguard 这工作正常......我使用的 RoboGuice 版本是 3.0