给定 ClassA 和 SubclassA,如果我使用 Google Guice 将 ClassA 绑定到 SubclassA,那么 SubclassA 是否会作为调用 ClassA 的实例注入?
Given ClassA and SubclassA, if I use Google Guice to bind ClassA to SubclassA then will SubclassA be injected as an instance where ClassA gets called?
假设我遇到这样的场景:
@Data
public class ClassA {
private final String name = "ClassA";
public ClassA(){
//This constructor gets called anyway. Why?
}
}
@Data
public class SubclassA extends ClassA {
private final String subname = "SubclassA";
@Inject
public SubclassA(){
//I would expect for ONLY this constructor to be called.
}
}
public class MyModule extends AbstractModule {
@Override
protected void setup(){
bind(ClassA.class).to(SubclassA.class);
}
}
public class Main {
public static void main(String [] args){
Injector injector = Guice.createInjector(new MyModule());
ClassA classA = injector.getInstance(ClassA.class);
}
}
我的一些问题:
- 为什么两个构造函数都被调用了?
- 对象classA是ClassA还是SubclassA的实例?
谢谢
对象classA是ClassA还是SubclassA的实例?
严格来说,classA 的类型是 SubClassA。
为什么两个构造函数都被调用了?
因为SubClassA是ClassA的子class,所以在创建SubClassA的实例时,它的父class的构造函数也会被调用。
假设我遇到这样的场景:
@Data
public class ClassA {
private final String name = "ClassA";
public ClassA(){
//This constructor gets called anyway. Why?
}
}
@Data
public class SubclassA extends ClassA {
private final String subname = "SubclassA";
@Inject
public SubclassA(){
//I would expect for ONLY this constructor to be called.
}
}
public class MyModule extends AbstractModule {
@Override
protected void setup(){
bind(ClassA.class).to(SubclassA.class);
}
}
public class Main {
public static void main(String [] args){
Injector injector = Guice.createInjector(new MyModule());
ClassA classA = injector.getInstance(ClassA.class);
}
}
我的一些问题:
- 为什么两个构造函数都被调用了?
- 对象classA是ClassA还是SubclassA的实例?
谢谢
对象classA是ClassA还是SubclassA的实例? 严格来说,classA 的类型是 SubClassA。
为什么两个构造函数都被调用了? 因为SubClassA是ClassA的子class,所以在创建SubClassA的实例时,它的父class的构造函数也会被调用。