简体   繁体   中英

Get the implementation type for an interface in Guice

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM