blob: 75dcc9d9bc4f34e7cdaf7ed39b32b7a61aeb76af [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 */
limpbizkit5ae41eb2009-06-06 17:51:27 +000027public final class SourceProvider {
limpbizkit6663d022008-06-19 07:57:55 +000028
29 /** Indicates that the source is unknown. */
30 public static final Object UNKNOWN_SOURCE = "[unknown source]";
31
32 private final ImmutableSet<String> classNamesToSkip;
33
limpbizkit6663d022008-06-19 07:57:55 +000034 public static final SourceProvider DEFAULT_INSTANCE
35 = new SourceProvider(ImmutableSet.of(SourceProvider.class.getName()));
36
37 private SourceProvider(Iterable<String> classesToSkip) {
38 this.classNamesToSkip = ImmutableSet.copyOf(classesToSkip);
39 }
40
41 /** Returns a new instance that also skips {@code moreClassesToSkip}. */
42 public SourceProvider plusSkippedClasses(Class... moreClassesToSkip) {
43 return new SourceProvider(concat(classNamesToSkip, asStrings(moreClassesToSkip)));
44 }
45
46 /** Returns the class names as Strings */
47 private static List<String> asStrings(Class... classes) {
48 List<String> strings = Lists.newArrayList();
49 for (Class c : classes) {
50 strings.add(c.getName());
51 }
52 return strings;
53 }
54
limpbizkit6663d022008-06-19 07:57:55 +000055 /**
56 * Returns the calling line of code. The selected line is the nearest to the top of the stack that
57 * is not skipped.
58 */
59 public StackTraceElement get() {
60 for (final StackTraceElement element : new Throwable().getStackTrace()) {
61 String className = element.getClassName();
62 if (!classNamesToSkip.contains(className)) {
63 return element;
64 }
65 }
66 throw new AssertionError();
67 }
68}