blob: 29f4508a494a0814fa95ca75a8d3412ac0dc64ce [file] [log] [blame]
limpbizkit6663d022008-06-19 07:57:55 +00001/**
2 * Copyright (C) 2006 Google Inc.
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
17package com.google.inject.internal;
18
limpbizkit53664a72009-02-21 00:25:27 +000019import static com.google.inject.internal.Iterables.concat;
limpbizkit6663d022008-06-19 07:57:55 +000020import java.util.List;
limpbizkit6663d022008-06-19 07:57:55 +000021
22/**
23 * Provides access to the calling line of code.
24 *
25 * @author crazybob@google.com (Bob Lee)
26 */
27public class SourceProvider {
28
29 /** Indicates that the source is unknown. */
30 public static final Object UNKNOWN_SOURCE = "[unknown source]";
31
32 private final ImmutableSet<String> classNamesToSkip;
33
34 public SourceProvider() {
35 this.classNamesToSkip = ImmutableSet.of(SourceProvider.class.getName());
36 }
37
38 public static final SourceProvider DEFAULT_INSTANCE
39 = new SourceProvider(ImmutableSet.of(SourceProvider.class.getName()));
40
41 private SourceProvider(Iterable<String> classesToSkip) {
42 this.classNamesToSkip = ImmutableSet.copyOf(classesToSkip);
43 }
44
45 /** Returns a new instance that also skips {@code moreClassesToSkip}. */
46 public SourceProvider plusSkippedClasses(Class... moreClassesToSkip) {
47 return new SourceProvider(concat(classNamesToSkip, asStrings(moreClassesToSkip)));
48 }
49
50 /** Returns the class names as Strings */
51 private static List<String> asStrings(Class... classes) {
52 List<String> strings = Lists.newArrayList();
53 for (Class c : classes) {
54 strings.add(c.getName());
55 }
56 return strings;
57 }
58
limpbizkit6663d022008-06-19 07:57:55 +000059 /**
60 * Returns the calling line of code. The selected line is the nearest to the top of the stack that
61 * is not skipped.
62 */
63 public StackTraceElement get() {
64 for (final StackTraceElement element : new Throwable().getStackTrace()) {
65 String className = element.getClassName();
66 if (!classNamesToSkip.contains(className)) {
67 return element;
68 }
69 }
70 throw new AssertionError();
71 }
72}