0

I'm using Guice 3 to do dependency injection.

I have a particular use case where I need to know what implementation type has been bound to the interface. Is there a mechanism is Guice that allows us to do this?

Pradeep Gollakota
  • 2,161
  • 16
  • 24
  • `.getClass().getName()`?... But, kinda flies in the face of dependency injection principles... – Lucas May 28 '13 at 20:25
  • I can't do .getClass() because I don't even have an instance of the object I'm trying to find the class of. I suppose I can instantiate a mock instance and then do that. I also realize that it flies in the face of dependency injection. But I need this to be able to correctly write class information into a Sequence File in hadoop. – Pradeep Gollakota May 29 '13 at 15:08

1 Answers1

2

For such purposes Guice provides Extensions SPI.

You need to extend the DefaultBindingTargetVisitor (if you wish to override selective methods) and override the visit(Binding binding) you wish to inspect.

public class MyBindingsVisitor extends DefaultBindingTargetVisitor<Object, String>{

    public String visit(InstanceBinding<? extends Object> binding){
        Key<? extends Object> key = binding.getKey();
            System.out.println("Key :" + key.getTypeLiteral());
            System.out.println("Annotation : " + key.getAnnotation());
            System.out.println("Source : " + binding.getSource());
            System.out.println("Instance : "+binding.getInstance().toString());
            return visitOther(binding);
    }
}

Now, we need the injector to visit the bindings.

for(Binding<?> binding : injector.getBindings().values()){
    System.out.println(binding.acceptTargetVisitor(new MyBindingsVisitor()));
}

These bindings are complete bindings and hence are termed as the Injector Bindings.