当时我想将presenter注入到Activity中,代码如下,make Projiect的时候不通过 百思不得其解
坑1
class MainActivity : AppCompatActivity() ,MainContract.View {
@Inject
var mPresenter : MainContract.Presenter ? = null
override fun onCreate(savedInstanceState: Bundle?) {
//******//
super.onCreate(savedInstanceState)
DaggerMainActivityComponent.builder().build().inject(this)
mPresenter?.subscribe()
}
@Module
inner class PresenterModules {
@Provides
fun providePresenter(): MainContract.Presenter {
return MainPresenter(this@MainActivity)
}
}
}
@Component(modules = arrayOf(MainActivity.PresenterModules::class))
interface MainActivityComponent {
fun inject(activity: MainActivity)
}
然后我将kotlin 代码 转成字节码后再转成java代码,发现Presenter是私有的.
而我们都知道,注入的对象不可以是私有的
public final class MainActivity extends AppCompatActivity implements View {
@Inject
@Nullable
private Presenter mPresenter;
-----省略
}
//于是将上述代码改成
@Inject
@JvmField
var mPresenter : MainContract.Presenter ? = null
//或则
@Inject
lateinit mPresenter : MainContract.Presenter
即可编译成功
坑2
@Inject
@JvmField
// @Named("preneter")// 错误 正确的做法如下
@field:[Named("preneter")]
var mPresenter : MainContract.Presenter ? = null
@Module
inner class PresenterModules {
@Provides
@Named("preneter")
fun providePresenter(): MainContract.Presenter {
return MainPresenter(this@MainActivity)
}
@Provides
@Named("hello")
fun provide():String{
return "hello"
}
}
网友评论