lex
lex

Reputation: 103

Inject fields in a generic class

I have an Activity of the following form:

public class MyActivity<T extends AbstractDescriptionItem> extends BaseActivity[...]

when I define:

@ContributesAndroidInjector
abstract MyActivity contributeMyActivity();

I get this error:

error: [Dagger/MembersInjection] [dagger.android.AndroidInjector.inject(T)] Cannot inject members into raw type com.test MyActivity

if I try:

@ContributesAndroidInjector
abstract MyActivity<AbstractDescriptionItem> contributeMyActivity();

I get

error: @ContributesAndroidInjector methods cannot return parameterized types

Is there any way to inject dependencies in MyActivity without changing the architecture?

Upvotes: 2

Views: 857

Answers (1)

Emre Eran
Emre Eran

Reputation: 336

The solution I came up with is to implement the different cases of the Activity/Fragment with type parameters and contribute the implementations. It will be something like this for your case:

public abstract class MyActivity<T extends AbstractDescriptionItem> extends BaseActivity[...]

Let's say you have a BookDescriptionItem class extending AbstractDescriptionItem :

public class BookDescriptionActivity extends MyActivity<BookDescriptionItem>

Finally, contribute the implementations:

@ContributesAndroidInjector
abstract BookDescriptionActivity contributeBookDescriptionActivity();

Upvotes: 1

Related Questions