01: /**
02: * Copyright (C) 2006 Google Inc.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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: */package com.google.inject.util;
16:
17: import com.google.inject.spi.SourceProviders;
18: import static com.google.inject.util.ReferenceType.SOFT;
19: import static com.google.inject.util.ReferenceType.WEAK;
20: import java.io.IOException;
21: import java.lang.reflect.Constructor;
22: import java.lang.reflect.Member;
23: import java.util.Map;
24:
25: /**
26: * Creates stack trace elements for members.
27: *
28: * @author crazybob@google.com (Bob Lee)
29: */
30: public class StackTraceElements {
31:
32: static final Map<Class<?>, LineNumbers> lineNumbersCache = new ReferenceCache<Class<?>, LineNumbers>(
33: WEAK, SOFT) {
34: protected LineNumbers create(Class<?> key) {
35: try {
36: return new LineNumbers(key);
37: } catch (IOException e) {
38: throw new RuntimeException(e);
39: }
40: }
41: };
42:
43: public static Object forMember(Member member) {
44: if (member == null) {
45: return SourceProviders.UNKNOWN_SOURCE;
46: }
47:
48: Class declaringClass = member.getDeclaringClass();
49: LineNumbers lineNumbers = lineNumbersCache.get(declaringClass);
50: Integer lineNumber = lineNumbers.getLineNumber(member);
51: String memberName = member instanceof Constructor ? "<init>"
52: : member.getName();
53: StackTraceElement element = new StackTraceElement(
54: declaringClass.getName(), memberName, lineNumbers
55: .getSource(), lineNumber == null ? lineNumbers
56: .getFirstLine() : lineNumber);
57: return element;
58: }
59:
60: public static Object forType(Class<?> implementation) {
61: LineNumbers lineNumbers = lineNumbersCache.get(implementation);
62: return new StackTraceElement(implementation.getName(), "class",
63: lineNumbers.getSource(), lineNumbers.getFirstLine());
64: }
65: }
|