0

I would like to annotate a constructor like this:

@Inject Constructor(
  @Some("abc") String abc,
  @Some("rst") String rst,
  @Some("xyz") BigInteger xyz
)

Now when creating an instance of that class I would like to provide values for abc, rst, and xyz to dynamically depend on the values of the @Some annotation.

That is I am NOT looking for annotatedWith or annotatedWithName but I am looking for something that allows me to do the injection dynamically, i.e. something hypothetically like:

@DynamicProvider
public T provide(Context[T] injectionContext) {
  if (injectionContext.getType == String.class) {
    return (T) lookupString(injectionContext.getAnnotation(Some.class).value)
  }
  // etc
}
scravy
  • 11,904
  • 14
  • 72
  • 127
  • I wrote a library called `sangria-contextual` that seems to do what you want: https://github.com/tavianator/sangria/blob/master/sangria-contextual/src/main/java/com/tavianator/sangria/contextual/ContextSensitiveProvider.java – Tavian Barnes Apr 15 '16 at 18:39
  • Your library looks pretty damn like what I was looking for, but when I played around with it, it would'nt work for me. My constructor looks like the one in my question, but when I use the `ContextSensitiveBinder` it only ever calls `getInUnknownContext` in my `ContextSensitiveProvider` (not `getInContext`). Also I am interested in the actual parameter, not only the InjectionPoint (that's why I have two `String` parameters with different annotations in the example). I came up with a different solution on my own today, see the answers. – scravy Apr 16 '16 at 22:59
  • okay okay, here it is: http://stackoverflow.com/questions/14680124/how-to-bind-with-provider-which-uses-annotation-value-in-guice/36670790#36670790 – scravy Apr 16 '16 at 23:05
  • You can look for yourself in `injectionPoint.getDependencies()` to find the parameter itself. (For version 2 I plan to pass `Dependency` instead of `InjectionPoint` to make this easier.) Weird that `getInUnknownContext()` is being called though, I'd love a bug report if you have a reproducer. – Tavian Barnes Apr 17 '16 at 16:22

0 Answers0