Android Dagger2 @Inject必须具体到某个类,不支持注入子类赋值给父类

我们知道java的多态支持声明一个父类对象,然后实例化一个子类对象赋值给它

但是Dagger并不支持这种多态,我们可以写个例子验证下,直接上代码

1
2
3
public interface Person {
String saySomething();
}

Click and drag to move

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Student implements Person {

public String name;

// 注入的是子类
@Inject
public Student() {
this.name = "野猿新一";
}

@Override
public String toString() {
return String.format("我的名字叫%s啦", name);
}

@Override
public String saySomething() {
return toString();
}
}

Click and drag to move

1
2
3
4
@Component
public interface MainActivityComponent {
void inject(MainActivity activity);
}

Click and drag to move

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class MainActivity extends AppCompatActivity {

// 这里声明的是父类
@Inject
Person student;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

DaggerMainActivityComponent.create().inject(this);
TextView textView = findViewById(R.id.text);
textView.setText(student.saySomething());
}
}

Click and drag to move

直接运行下,结果无法编译通过,报如下错误

1
2
3
4
5
error: [Dagger/MissingBinding] com.him.hisapp.Person cannot be provided without an @Provides-annotated method.
com.him.hisapp.Person is injected at
com.him.hisapp.MainActivity.student
com.him.hisapp.MainActivity is injected at
com.him.hisapp.MainActivityComponent.inject(com.him.hisapp.MainActivity)

Click and drag to move

计时用Modele也是没用的

1
2
3
4
5
6
7
@Module
public class MainModule {
@Provides
public Student providePerson() {
return new Student();
}
}

Click and drag to move

除非我们将Modele中providePerson方法返回类型明确声明为父类Person

1
2
3
4
5
6
7
@Module
public class MainModule {
@Provides
public Person providePerson() {
return new Student();
}
}

Click and drag to move

其实很容易知道为什么Dagger依赖注入不支持多态的原因,我们假设需要注入一个Object的对象,而项目中如果有很多@Inject标识的构造方法,这些构造方法生成的对象都是Object的子类对象,那么Dagger就不知道要注入哪一个,就无法编译通过。