get hold of annotations while inside a @Provides method

22 views
Skip to first unread message

Bert Robben

unread,
Jun 6, 2016, 11:21:56 AM6/6/16
to google-guice
Hi,

Is it possible to get hold of annotations on the injection point inside a provider ?

To make this more clear, I'd like to do the following, 

Given a number of service classes:

class A { @Named("B") X x; ... }
class B { @Named("C") X x;... }
class C { ... }
...

And this module:

public class MyModule extends AbstractModule {

@Provides
@Named("A")
public X a(Injector inj) {
return createX(inj.getProvider(A.class)));
}

@Provides
@Named("B")
public X b(Injector inj) {
return createX(inj.getProvider(B.class)));
}

@Provides
@Named("C")
public X c(Injector inj) {
return createX(inj.getProvider(C.class)));
}

...
@Override
protected void configure() {
}

        protected X createX(...) {
             return ...;
        }
}

but then without all the duplication of the providers. So ideally I'd like to have this @Named() annotation as a parameter to the provider method.


So something like:

@Provides
public X createX(Y y, Injector inj) { // no idea what this Y would be
                String name = getValueOfNamedAnnotation(y);
return createX(inj.getProvider(getImplementationClassFor(y))));
}

Is that possible?

thanks,

Bert
Reply all
Reply to author
Forward
0 new messages