Kelvin Chung
Kelvin Chung

Reputation: 1377

Constructor bindings and telling parameters apart

Suppose I have a third-party class:

public class ThirdParty {
    public ThirdParty(String arg1, String arg2);
}

Since this is third-party, I cannot add my own @Inject annotation, forcing me to use bind-to-constructor. The question is how I can create a ThirdParty with arg1 and arg2 different. In essence, add "Named" annotations from the outside, so to speak.

Upvotes: 0

Views: 44

Answers (1)

condit
condit

Reputation: 10962

How about something like:

class ProvidesExample {

  static class ThirdParty {
    public ThirdParty(String arg1, String arg2) {}
  }

  static class Module extends AbstractModule {

    @Override
    protected void configure() {
      bindConstant().annotatedWith(Names.named("arg1")).to("Argument 1");
      bindConstant().annotatedWith(Names.named("arg2")).to("Argument 2");
    }

    @Provides
    ThirdParty getThirdParth(@Named("arg1") String arg1, @Named("arg2") String arg2) {
      return new ThirdParty(arg1, arg2);
    }

  }
}

Upvotes: 3

Related Questions