1 /* 2 * Copyright (C) 2011 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 * use this file except in compliance with the License. You may obtain a copy of 6 * 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, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations under 14 * the License. 15 */ 16 17 package com.google.inject.spi; 18 19 import com.google.inject.Binder; 20 import com.google.inject.Binding; 21 import com.google.inject.Injector; 22 import com.google.inject.internal.util.StackTraceElements; 23 24 import java.lang.reflect.Member; 25 26 /** 27 * A combination of a {@link Dependency} and the {@link Binding#getSource() 28 * source} where the dependency was bound. 29 * 30 * @author sameb@google.com (Sam Berlin) 31 * @since 4.0 32 */ 33 public final class DependencyAndSource { 34 private final Dependency<?> dependency; 35 private final Object source; 36 DependencyAndSource(Dependency<?> dependency, Object source)37 public DependencyAndSource(Dependency<?> dependency, Object source) { 38 this.dependency = dependency; 39 this.source = source; 40 } 41 42 /** 43 * Returns the Dependency, if one exists. For anything that can be referenced 44 * by {@link Injector#getBinding}, a dependency exists. A dependency will not 45 * exist (and this will return null) for types initialized with 46 * {@link Binder#requestInjection} or {@link Injector#injectMembers(Object)}, 47 * nor will it exist for objects injected into Providers bound with 48 * LinkedBindingBuilder#toProvider(Provider). 49 */ getDependency()50 public Dependency<?> getDependency() { 51 return dependency; 52 } 53 54 /** 55 * Returns a string describing where this dependency was bound. If the binding 56 * was just-in-time, there is no valid binding source, so this describes the 57 * class in question. 58 */ getBindingSource()59 public String getBindingSource() { 60 if (source instanceof Class) { 61 return StackTraceElements.forType((Class) source).toString(); 62 } else if (source instanceof Member) { 63 return StackTraceElements.forMember((Member) source).toString(); 64 } else { 65 return source.toString(); 66 } 67 } 68 69 @Override toString()70 public String toString() { 71 Dependency<?> dep = getDependency(); 72 Object source = getBindingSource(); 73 if (dep != null) { 74 return "Dependency: " + dep + ", source: " + source; 75 } else { 76 return "Source: " + source; 77 } 78 } 79 }