Context
I want to automatically inject configuration items using Guice. My configuration framework is typesafe's config.
public class MyObject {
@Configuration("value") int value;
}
To do that, I wrote an annotation.
// Annotations skipped, but correct
public @interface Configuration {
String value();
}
And I wrote a module. This module checks for all types to inject, then allows the injection itself.
public class ConfigurationModule extends AbstractModule {
@Override protected void configure() {
final Config config = ConfigFactory.load();
class ConfigurationMembersInjector<T> implements MembersInjector<T> {
private final Field field;
ConfigurationMembersInjector(Field field) {
this.field = field;
field.setAccessible(true);
}
@Override public void injectMembers(T t) {
try {
String key = field.getAnnotation(Configuration.class).value();
field.set(t, config.getXxxx()); // what to write?
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
class ConfigurationTypeListener implements TypeListener {
@Override public <T> void hear(TypeLiteral<T> typeLiteral, TypeEncounter<T> typeEncounter) {
for (Field field : typeLiteral.getRawType().getDeclaredFields()) {
if (field.isAnnotationPresent(Configuration.class)) {
typeEncounter.register(new ConfigurationMembersInjector<T>(field));
}
}
}
}
bindListener(Matchers.any(), new ConfigurationTypeListener());
}
}
Question
How do I automatically convert a configuration item to a specific yet unknown type? Is there a way to say "I want this item converted as this type"? Also, is there a way to "register" custom converters?
Or else, do I have to write my own conversion mechanism?