Your real request, about injecting the creation context, is not possible and will not be possible in Guice. (direct link to bug)
A couple other ideas:
If your use-case can suffice with read-only properties, use
Names.bindProperties
which will allow an entireProperties
instance (orMap<String, String>
) to be bound to constants with appropriate@Named
annotations. Like otherbindConstant
calls, this will even cast to appropriate primitive types for you, or anything else you bind usingconvertToTypes
.If you're just looking for an individual Map per injecting class, don't forget that you can write your own factory.
class PreferenceMapOracle { private static final Map<Class<?>, Map<String, String>> prefMap = Maps.newHashMap(); public Map<String, String> mapForClass(Class<?> clazz) { if (prefMap.contains(clazz)) { return prefMap.get(clazz); } Map<String, String> newMap = Maps.newHashMap(); prefMap.put(clazz, newMap); return newMap; } } class GuiceUser { private final Map<String, String> preferences; @Inject GuiceUser(PreferenceMapOracle oracle) { preferences = oracle.mapForClass(getClass()); } }
Nothing built into Guice will automatically reflect across your
Preferences
interface and create a bean-style implementation where there was none. You could probably write your own clever framework with liberal use of dynamic proxy objects, or with a package that provides nifty reflective support like GSON. You will still need to provide those reflectively-created interfaces one way or another, but I could easily imagine a call like:preferences = oracle.getPrefs(Preferences.class);