• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 The Dagger Authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package dagger.hilt.android.migration;
18 
19 import java.lang.annotation.ElementType;
20 import java.lang.annotation.Target;
21 
22 /**
23  * When placed on an {@link dagger.hilt.android.AndroidEntryPoint}-annotated activity / fragment /
24  * view / etc, allows injection to occur optionally based on whether or not the application is using
25  * Hilt.
26  *
27  * <p>When using this annotation, you can use {@link OptionalInjectCheck#wasInjectedByHilt} to check
28  * at runtime if the annotated class was injected by Hilt. Additionally, this annotation will also
29  * cause a method, {@code wasInjectedByHilt} to be generated in the Hilt base class as well, that
30  * behaves the same as {@link OptionalInjectCheck#wasInjectedByHilt}. The method is available to
31  * users that extend the Hilt base class directly and don't use the Gradle plugin.
32  *
33  * <p>Example usage:
34  *
35  * <pre><code>
36  * {@literal @}OptionalInject
37  * {@literal @}AndroidEntryPoint
38  * public final class MyFragment extends Fragment {
39  *
40  *   {@literal @}Inject Foo foo;
41  *
42  *   {@literal @}Override
43  *   public void onAttach(Activity activity) {
44  *     // Injection will happen here, but only if the Activity and the Application are also
45  *     // AndroidEntryPoints and were injected by Hilt.
46  *     super.onAttach(activity);
47  *     if (!OptionalInjectCheck.wasInjectedByHilt(this)) {
48  *       // Get Dagger components the previous way and inject.
49  *     }
50  *   }
51  * }
52  * </code></pre>
53  *
54  * <p>This is useful for libraries that have to support Hilt users as well as non-Hilt users.
55  * Injection will happen if the parent type (e.g. the activity of a fragment) is an {@link
56  * dagger.hilt.android.AndroidEntryPoint} annotated class and if that parent was also injected via
57  * Hilt.
58  *
59  * @see OptionalInjectCheck
60  * @see <a href="https://dagger.dev/hilt/optional-inject">Optional injection</a>
61  */
62 @Target(ElementType.TYPE)
63 public @interface OptionalInject {}
64