Skip to content

InspectingModules

Googler edited this page Jan 18, 2020 · 6 revisions

Inspecting what makes up a Module & examining Bindings

Elements SPI

Guice provides a rich service provider interface (SPI) for all the elements that make up a module. You can use this SPI to learn what bindings are in a module and even rewrite some of those bindings. Modules.override is written entirely using this SPI.

Examining Elements

The Elements class provides access to each Element within a Module. You can use this class to get individual elements from a module and take action upon them. Each Element has an acceptVisitor method that takes an ElementVisitor. You can use DefaultElementVisitor to simplify writing a visitor.

  void warnAboutStaticInjections(Module... modules) {
    for(Element element : Elements.getElements(modules)) {
      element.acceptVisitor(new DefaultElementVisitor<Void>() {
          @Override public void visit(StaticInjectionRequest request) {
            System.out.println("You shouldn't be using static injection at: " + request.getSource());
          }
      });
    }
  }

Manipulating Modules

You can use the SPI to do anything from stripping out elements to rewriting elements to adding new elements. When you've finished wiring your elements, you can turn them back into a module.

  Module stripStaticInjections(Module... modules) {
    final List<Element> noStatics = Lists.newArrayList();
    for(Element element : Elements.getElements(modules)) {
      element.acceptVisitor(new DefaultElementVisitor<Void>() {
        @Override public void visit(StaticInjectionRequest request) {
          // override to not call visitOther
        }

        @Override public void visitOther(Element element) {
          noStatics.add(element);
        }
      });
    }
    return Elements.getModule(noStatics);
  }

Binding Binoculars

The most common Element is a Binding. Bindings have more configuration than other elements and can be inspected in more ways. You can visit a binding's scope using Binding.acceptScopingVisitor), or figure out what kind of binding it is using Binding.acceptTargetVisitor. Each of these methods have their own default visitors (DefaultBindingScopingVisitor and DefaultBindingTargetVisitor, respectively) to make visiting easier.

Bindings can either be "Module bindings" or "Injector bindings". Injector bindings are bindings retrieved from an injector (see the Injector javadoc). Module bindings are bindings retrieved using the Elements SPI. The Binding javadoc explains the difference between these in more detail.

Extensions

Guice 3.0 adds the ability for extensions to write their own SPI. See ExtensionSPI for details.

Clone this wiki locally