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 explicitly in a 28 * module using {@link com.google.inject.Binder#convertToTypes(Matcher, TypeConverter) 29 * convertToTypes()} statements: 30 * 31 * <pre> 32 * convertToTypes(Matchers.only(TypeLiteral.get(DateTime.class)), new DateTimeConverter()); 33 * </pre> 34 * 35 * @author jessewilson@google.com (Jesse Wilson) 36 * @since 2.0 37 */ 38 public final class TypeConverterBinding implements Element { 39 private final Object source; 40 private final Matcher<? super TypeLiteral<?>> typeMatcher; 41 private final TypeConverter typeConverter; 42 43 /** @since 3.0 */ TypeConverterBinding( Object source, Matcher<? super TypeLiteral<?>> typeMatcher, TypeConverter typeConverter)44 public TypeConverterBinding( 45 Object source, Matcher<? super TypeLiteral<?>> typeMatcher, TypeConverter typeConverter) { 46 this.source = checkNotNull(source, "source"); 47 this.typeMatcher = checkNotNull(typeMatcher, "typeMatcher"); 48 this.typeConverter = checkNotNull(typeConverter, "typeConverter"); 49 } 50 51 @Override getSource()52 public Object getSource() { 53 return source; 54 } 55 getTypeMatcher()56 public Matcher<? super TypeLiteral<?>> getTypeMatcher() { 57 return typeMatcher; 58 } 59 getTypeConverter()60 public TypeConverter getTypeConverter() { 61 return typeConverter; 62 } 63 64 @Override acceptVisitor(ElementVisitor<T> visitor)65 public <T> T acceptVisitor(ElementVisitor<T> visitor) { 66 return visitor.visit(this); 67 } 68 69 @Override applyTo(Binder binder)70 public void applyTo(Binder binder) { 71 binder.withSource(getSource()).convertToTypes(typeMatcher, typeConverter); 72 } 73 74 @Override toString()75 public String toString() { 76 return typeConverter 77 + " which matches " 78 + typeMatcher 79 + " (bound at " 80 + Errors.convert(source) 81 + ")"; 82 } 83 } 84