vendredi 27 avril 2018

Pass a variable as a parameter while creating its object

I want to inject a variable as a parameter while creating its object using Guice. I am able to achieve it without using guice by using below code.

class A{
       private CountDownLatchFactory countDownLatchFactory;
       A(CountDownLatchFactory countDownLatchFactory){
             this.countDownLatchFactory = countDownLatchFactory;
       }
       public void createTimer(List<String> targets){
           // doing some stuff
           countDownLatchFactory.create(targets.size());
          //doing some stuff
       }
  }

  class B{
    private CountDownLatchFactory countDownLatchFactory;
       B(CountDownLatchFactory countDownLatchFactory){
             this.countDownLatchFactory = countDownLatchFactory;
        }    

    public void usingTimer(){
    //doing some stuff
    countDownLatchFactory.getCountDownLatch().countDown();
    //doing some stuff
   }
}

public class CountDownLatchFactory{

    private CountDownLatch responseLatch;

    /**
     * @param numTargets
     * @return
     */
    public void create(int numTargets) {
        responseLatch = new CountDownLatch(numTargets);
    }

    public CountDownLatch getCountDownLatch(){
        return responseLatch;
    }
}

The thing i am not able to understand is how can guice can can create a object using a parameter. The parameter can only be supplied using function of the class and if guice cant do that. Is there is a better way of doing it?

Aucun commentaire:

Enregistrer un commentaire