• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (C) 2008 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 static com.google.common.base.Preconditions.checkNotNull;
20 
21 import com.google.inject.Binder;
22 import com.google.inject.TypeLiteral;
23 import com.google.inject.internal.Errors;
24 import com.google.inject.matcher.Matcher;
25 
26 /**
27  * Registration of type converters for matching target types. Instances are created
28  * explicitly in a module using {@link com.google.inject.Binder#convertToTypes(Matcher,
29  * TypeConverter) convertToTypes()} statements:
30  * <pre>
31  *     convertToTypes(Matchers.only(TypeLiteral.get(DateTime.class)), new DateTimeConverter());</pre>
32  *
33  * @author jessewilson@google.com (Jesse Wilson)
34  * @since 2.0
35  */
36 public final class TypeConverterBinding implements Element {
37   private final Object source;
38   private final Matcher<? super TypeLiteral<?>> typeMatcher;
39   private final TypeConverter typeConverter;
40 
41   /** @since 3.0 */
TypeConverterBinding(Object source, Matcher<? super TypeLiteral<?>> typeMatcher, TypeConverter typeConverter)42   public TypeConverterBinding(Object source, Matcher<? super TypeLiteral<?>> typeMatcher,
43       TypeConverter typeConverter) {
44     this.source = checkNotNull(source, "source");
45     this.typeMatcher = checkNotNull(typeMatcher, "typeMatcher");
46     this.typeConverter = checkNotNull(typeConverter, "typeConverter");
47   }
48 
getSource()49   public Object getSource() {
50     return source;
51   }
52 
getTypeMatcher()53   public Matcher<? super TypeLiteral<?>> getTypeMatcher() {
54     return typeMatcher;
55   }
56 
getTypeConverter()57   public TypeConverter getTypeConverter() {
58     return typeConverter;
59   }
60 
acceptVisitor(ElementVisitor<T> visitor)61   public <T> T acceptVisitor(ElementVisitor<T> visitor) {
62     return visitor.visit(this);
63   }
64 
applyTo(Binder binder)65   public void applyTo(Binder binder) {
66     binder.withSource(getSource()).convertToTypes(typeMatcher, typeConverter);
67   }
68 
toString()69   @Override public String toString() {
70     return typeConverter + " which matches " + typeMatcher
71         + " (bound at " + Errors.convert(source) + ")";
72   }
73 }
74