0

I am using Dagger dependency injection to initiate a list of Foo elements that will get passed to another object. Here is essentially the code:

@Provides
@Singleton
public List<Foo> provideList(@Named("foo1") Foo foo1, @Named("foo2") Foo foo2) {
    List<Foo> list = new ArrayList<>();
    list.add(foo1);
    list.add(foo2);
    return list;
}

As time progresses, we expect to add more and more Foo arguments to this method. To make the code more durable, I'd like to do something like the following:

@Provides
@Singleton
public List<Foo> provideList(@Named("foo1") Foo foo1, @Named("foo2") Foo foo2) {
    List<Foo> list = new ArrayList<>();

    args.forEach(arg -> {
        if (arg instanceof Foo) list.add((Foo) arg);
    });

    return list;
}

Is anything like this possible in Java?

chemdog95
  • 366
  • 4
  • 16
  • Please clarify what you mean by Constructor Arguments. Your code does not show any Constructors, do you mean functions/methods instead? – Scorix Sep 12 '18 at 16:17
  • 1
    Not while having a pre-defined number of params. You could use a method signature like `provideList(Foo... foos)` and then have an array of `Foo` objects you can iterate through. Also, your first code block can be simplified to `Arrays.asList(foo1, foo2);` – Taylor Sep 12 '18 at 16:17
  • Why don't you use varargs and can drop the @Named annotation. – Ashraff Ali Wahab Sep 12 '18 at 16:20
  • 1
    `return List.of(foo1, foo2);`. Unless you change to varargs, that's about as concise as you can get. – Andy Turner Sep 12 '18 at 16:22

0 Answers0