Search code examples
javadependency-injectionguice

Get all instances created by Guice Provider


Assuming a ClassX as:

class ClassX {
    
    int value;
    
    ClassX() {
        this.value = new Random().nextInt(10);
    }

    //equals and hashCode depend on "value"
}

If I have a Provider as:

@Provides
public ClassX createInstance() {
    return new ClassX();
}

Is there a way to inject all the instances created, so I can sum up all values in total? I tried something like:

@Inject
public Test(Set<ClassX> set) {
    this.set = set
}

int total() {
    return this.set.stream()
            .map(classX -> classX.value)
            .reduce(0, Integer::sum);
}

but it fails. Worth mentioning that I read about MultiBinder but I would need the instances in order to add them to the Set, so, does not seem an option for this case.


Solution

  • Would the simple case of just maintaining the list inside of the Provider do the trick? Work in your preferred method of thread safety around instances.

    class MyProvider implements Provider {
       Set<ClassX> instances = new HashSet<>();
    
       public ClassX get() {
            ClassX classX = new ClassX();
            instances.add(classX);
            return classX;
       }
    
       public Set<ClassX> getInstances() {
          // ... calculate what you need
       }
    }
    

    I don't believe there is any way to tell Guice to save all of the instances it's created or provided.