Reputation: 1254
I have a Car
class which extends Vehicle
class, i will be injecting some properties in the vehicle class.
Example EDITED
abstract class Vehicle {
@Inject
lateinit var default: Default
}
class Car @Inject constructor(): Vehicle() {
}
In my code everything works fine,
But one thing i need to know is that how the dagger injects the properties in base class or its hierarchy?
is this the proper way of injecting?
can anyone clarify this?
Upvotes: 4
Views: 1232
Reputation: 1567
But one thing i need to know is that how the dagger injects the properties in base class or its hierarchy?
For that you can look at the generated source files. In your case there will be something like that:
class Car_Factory implements Factory<Car> {
@Override
public Car get() {
return provideInstance(
defaultProvider
);
}
public static Car provideInstance(
Provider<Default> defaultProvider
) {
Car instance = new Car();
Vehicle_MembersInjector.injectDefault(instance, defaultProvider.get()); // just instance.default = default here
return instance;
}
}
As you can see it will create your instance and then will access it's fields (as long as they are public and writable).
is this the proper way of injecting?
It's not recommended way, as you're exposing the fields, which could be private (or protected), and you enabling someone else outside to modify, which violates encapsulation.
Therefore it's better to use constructor injection in this way:
abstract class Vehicle(protected val default: Default)
class Car @Inject constructor(default: Default) : Vehicle(default)
In this way Dagger will create your instance with already initialized fields, and won't be accessing them
Upvotes: 6