1 /*
2  * Copyright (C) 2020 The Android Open Source Project
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 com.android.car.dialer;
18 
19 import android.app.Application;
20 import android.content.Context;
21 
22 import androidx.annotation.NonNull;
23 import androidx.annotation.Nullable;
24 
25 import dagger.hilt.internal.GeneratedComponentManager;
26 
27 /** Util class to retrieve dagger components from context. */
28 public final class ComponentFetcher {
29 
30     /** Fetches the component {@code T} from context. */
from(@onNull Context context, Class<T> componentClass)31     public static <T> T from(@NonNull Context context, Class<T> componentClass) {
32         return fromObject(context, componentClass);
33     }
34 
35     /** Fetches the component {@code T} from application. */
from(@onNull Application application, Class<T> componentClass)36     public static <T> T from(@NonNull Application application, Class<T> componentClass) {
37         return fromObject(application, componentClass);
38     }
39 
fromObject(@onNull Object object, Class<T> componentClass)40     private static <T> T fromObject(@NonNull Object object, Class<T> componentClass) {
41         T component = componentClass.cast(from(object));
42         if (component == null) {
43             throw new IllegalArgumentException(
44                     "Given object doesn't have the component installed: "
45                             + componentClass.getName());
46         }
47         return component;
48     }
49 
50     @Nullable
from(@onNull Object object)51     private static <T> T from(@NonNull Object object) {
52         if (object instanceof GeneratedComponentManager<?>) {
53             return (T) ((GeneratedComponentManager<?>) object).generatedComponent();
54         }
55         return null;
56     }
57 
ComponentFetcher()58     private ComponentFetcher() {
59     }
60 }
61