1 /* 2 * Copyright (C) 2019 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; 18 19 import dagger.hilt.internal.GeneratedComponent; 20 import dagger.hilt.internal.GeneratedComponentManager; 21 import javax.annotation.Nonnull; 22 23 /** Static utility methods for accessing objects through entry points. */ 24 public final class EntryPoints { 25 26 /** 27 * Returns the entry point interface given a component or component manager. Note that this 28 * performs an unsafe cast and so callers should be sure that the given component/component 29 * manager matches the entry point interface that is given. 30 * 31 * @param component The Hilt-generated component instance. For convenience, also takes component 32 * manager instances as well. 33 * @param entryPoint The interface marked with {@link dagger.hilt.EntryPoint}. The {@link 34 * dagger.hilt.InstallIn} annotation on this entry point should match the component argument 35 * above. 36 */ 37 // Note that the input is not statically declared to be a Component or ComponentManager to make 38 // this method easier to use, since most code will use this with an Application or Activity type. 39 @Nonnull get(Object component, Class<T> entryPoint)40 public static <T> T get(Object component, Class<T> entryPoint) { 41 if (component instanceof GeneratedComponent) { 42 // Unsafe cast. There is no way for this method to know that the correct component was used. 43 return entryPoint.cast(component); 44 } else if (component instanceof GeneratedComponentManager) { 45 // Unsafe cast. There is no way for this method to know that the correct component was used. 46 return entryPoint.cast(((GeneratedComponentManager<?>) component).generatedComponent()); 47 } else { 48 throw new IllegalStateException( 49 String.format( 50 "Given component holder %s does not implement %s or %s", 51 component.getClass(), GeneratedComponent.class, GeneratedComponentManager.class)); 52 } 53 } 54 EntryPoints()55 private EntryPoints() {} 56 } 57