1 16 17 package com.google.inject.spi; 18 19 import java.util.Collections ; 20 import java.util.HashSet ; 21 import java.util.Set ; 22 23 29 public class SourceProviders { 30 31 private SourceProviders() {} 32 33 public static final Object UNKNOWN_SOURCE = "[unknown source]"; 34 35 static final SourceProvider DEFAULT_INSTANCE = new StacktraceSourceProvider(); 36 37 static Set <String > skippedClassNames = Collections.emptySet(); 38 39 static { 40 skip(SourceProviders.class); 41 skip(StacktraceSourceProvider.class); 42 } 43 44 52 public synchronized static void skip(Class <?> clazz) { 53 Set <String > copy = new HashSet <String >(); 54 copy.addAll(skippedClassNames); 55 copy.add(clazz.getName()); 56 skippedClassNames = Collections.unmodifiableSet(copy); 57 } 58 59 63 public synchronized static Set <String > getSkippedClassNames() { 64 return skippedClassNames; 65 } 66 67 static ThreadLocal <SourceProvider[]> localSourceProvider = 68 new ThreadLocal <SourceProvider[]>() { 69 protected SourceProvider[] initialValue() { 70 return new SourceProvider[] { DEFAULT_INSTANCE }; 71 } 72 }; 73 74 77 public static Object defaultSource() { 78 return localSourceProvider.get()[0].source(); 79 } 80 81 85 public static void withDefault( 86 SourceProvider sourceProvider, Runnable r) { 87 SourceProvider[] holder = localSourceProvider.get(); 89 SourceProvider previous = holder[0]; 90 try { 91 holder[0] = sourceProvider; 92 r.run(); 93 } finally { 94 holder[0] = previous; 95 } 96 } 97 98 static class StacktraceSourceProvider implements SourceProvider { 99 public Object source() { 100 Set <String > skippedClassNames = getSkippedClassNames(); 102 for (final StackTraceElement element : new Throwable ().getStackTrace()) { 103 String className = element.getClassName(); 104 if (!skippedClassNames.contains(className)) { 105 return element; 106 } 107 } 108 throw new AssertionError (); 109 } 110 } 111 } 112 | Popular Tags |