Dagger 2 - two provides method that provide same interface

后端 未结 4 1280
慢半拍i
慢半拍i 2020-12-24 05:33

lets say I have:

public interface Shape  {}


public class Rectangle implements Shape {

}

public class Circle implements Shape {

}

and I

4条回答
  •  余生分开走
    2020-12-24 06:10

    In addition to @Named and custom qualifiers (shown in other responses), you can also use a custom qualifier with an enum parameter:

    // Definition
    
    @Qualifier
    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ShapeType {
      ShapeTypeEnum value(); /* default ShapeTypeEnum.RECTANGLE; */
    }
    
    public enum ShapeTypeEnum {
      RECTANGLE, CIRCLE
    }
    
    // Usage
    
    @Provides @ShapeType(ShapeTypeEnum.RECTANGLE)
    public Shape provideRectangle() {
        return new Rectangle();
    }
    
    @Inject @ShapeType(ShapeTypeEnum.RECTANGLE) Shape rectangle;
    

    This is an hybrid between @Named (which requires String keys, which is error-prone and can't be auto-completed) and custom qualifiers (which requires a file for each implementation).

提交回复
热议问题