I'd like to be able to discover/inject the name of the method that created an object via assisted injection into the object that was created.
An example of what I want to do:
// what I want guice to create the implementation for this
interface Preferences {
Preference<String> firstName();
Preference<String> lastName();
// other preferences possibly of other types
}
// my interfaces and classes
interface Preference<T> {
T get();
void set(T value);
}
class StringPreference implements Preference<String> {
private final Map<String, Object> backingStore;
private final String key;
@Inject StringPreference(@FactoryMethodName String key,
Map<String, Object> backingStore) {
this.backingStore = backingStore;
this.key = key;
}
public String get() { return backingStore.get(key).toString(); }
public void set(String value) { backingStore.put(key, value); }
}
// usage
public void exampleUsage() {
Injector di = // configure and get the injector (probably somewhere else)
Preferences map = di.createInstance(Preferences.class);
Map<String, Object> backingStore = di.createInstance(...);
assertTrue(backingStore.isEmpty()); // passes
map.firstName().set("Bob");
assertEquals("Bob", map.firstName().get());
assertEquals("Bob", backingStore.get("firstName"));
map.lastName().set("Smith");
assertEquals("Smith", map.lastName().get());
assertEquals("Smith", backingStore.get("lastName"));
}
Unfortunately the only ways I've thought of so far to implement this is to
- extend assisted injection (via copy and paste) to add my functionality
- Write something very similar to assisted injection that does it for me
- write a lot of boilerplate that does this without guices help
I'm looking for a solution along the lines of:
- Some guice configuration or pattern that does this
- Some extension that does this
- Documentation/examples of places I can look that will help me write this myself
- Alternate patterns for the example app to accomplish what I want to do