Annotation Interface OptionalInject


@Target(TYPE) public @interface OptionalInject
When placed on an AndroidEntryPoint-annotated activity / fragment / view / etc, allows injection to occur optionally based on whether or not the application is using Hilt.

When using this annotation, you can use OptionalInjectCheck.wasInjectedByHilt(androidx.activity.ComponentActivity) to check at runtime if the annotated class was injected by Hilt. Additionally, this annotation will also cause a method, wasInjectedByHilt to be generated in the Hilt base class as well, that behaves the same as OptionalInjectCheck.wasInjectedByHilt(androidx.activity.ComponentActivity). The method is available to users that extend the Hilt base class directly and don't use the Gradle plugin.

Example usage:


 @OptionalInject
 @AndroidEntryPoint
 public final class MyFragment extends Fragment {

   @Inject Foo foo;

   @Override
   public void onAttach(Activity activity) {
     // Injection will happen here, but only if the Activity and the Application are also
     // AndroidEntryPoints and were injected by Hilt.
     super.onAttach(activity);
     if (!OptionalInjectCheck.wasInjectedByHilt(this)) {
       // Get Dagger components the previous way and inject.
     }
   }
 }
 

This is useful for libraries that have to support Hilt users as well as non-Hilt users. Injection will happen if the parent type (e.g. the activity of a fragment) is an AndroidEntryPoint annotated class and if that parent was also injected via Hilt.

See Also: