1 /*
2  * Copyright (C) 2011 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.inject.spi;
18 
19 import com.google.common.collect.ImmutableList;
20 import com.google.inject.Binder;
21 import com.google.inject.Binding;
22 import com.google.inject.matcher.Matcher;
23 import java.util.List;
24 
25 /**
26  * Binds keys (picked using a Matcher) to a provision listener. Listeners are created explicitly in
27  * a module using {@link Binder#bindListener(Matcher, ProvisionListener...)} statements:
28  *
29  * @author sameb@google.com (Sam Berlin)
30  * @since 4.0
31  */
32 public final class ProvisionListenerBinding implements Element {
33 
34   private final Object source;
35   private final Matcher<? super Binding<?>> bindingMatcher;
36   private final List<ProvisionListener> listeners;
37 
ProvisionListenerBinding( Object source, Matcher<? super Binding<?>> bindingMatcher, ProvisionListener[] listeners)38   ProvisionListenerBinding(
39       Object source, Matcher<? super Binding<?>> bindingMatcher, ProvisionListener[] listeners) {
40     this.source = source;
41     this.bindingMatcher = bindingMatcher;
42     this.listeners = ImmutableList.copyOf(listeners);
43   }
44 
45   /** Returns the registered listeners. */
getListeners()46   public List<ProvisionListener> getListeners() {
47     return listeners;
48   }
49 
50   /**
51    * Returns the binding matcher which chooses which bindings the listener should be notified of.
52    */
getBindingMatcher()53   public Matcher<? super Binding<?>> getBindingMatcher() {
54     return bindingMatcher;
55   }
56 
57   @Override
getSource()58   public Object getSource() {
59     return source;
60   }
61 
62   @Override
acceptVisitor(ElementVisitor<R> visitor)63   public <R> R acceptVisitor(ElementVisitor<R> visitor) {
64     return visitor.visit(this);
65   }
66 
67   @Override
applyTo(Binder binder)68   public void applyTo(Binder binder) {
69     binder
70         .withSource(getSource())
71         .bindListener(bindingMatcher, listeners.toArray(new ProvisionListener[listeners.size()]));
72   }
73 }
74