blob: 6c77047cc69743c9c51c3f48608e6807200564bb [file] [log] [blame]
crazybobleeabc4dd02007-02-01 01:44:36 +00001/**
2 * Copyright (C) 2006 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 */
crazyboblee235d0682007-01-31 02:25:21 +000016
17package com.google.inject;
18
19import java.util.Arrays;
20import java.util.Collection;
21import java.lang.reflect.Method;
22import java.lang.reflect.Constructor;
23import java.lang.reflect.Field;
24
25/**
26 * Implements formatting. Converts known types to readable strings.
27 *
28 * @author crazybob@google.com (Bob Lee)
29 */
30abstract class AbstractErrorHandler implements ErrorHandler {
31
32 public final void handle(String message, Object... arguments) {
33 for (int i = 0; i < arguments.length; i++) {
34 arguments[i] = convert(arguments[i]);
35 }
36 handle(String.format(message, arguments));
37 }
38
39 static Object convert(Object o) {
40 for (Converter<?> converter : converters) {
41 if (converter.appliesTo(o)) {
42 return converter.convert(o);
43 }
44 }
45 return o;
46 }
47
48 @SuppressWarnings("unchecked")
49 static Collection<Converter<?>> converters = Arrays.asList(
50 new Converter<Method>(Method.class) {
51 public String toString(Method m) {
52 return "method " + m.getDeclaringClass().getName() + "."
53 + m.getName() + "()";
54 }
55 },
56 new Converter<Constructor>(Constructor.class) {
57 public String toString(Constructor c) {
58 return "constructor " + c.getDeclaringClass().getName() + "()";
59 }
60 },
61 new Converter<Field>(Field.class) {
62 public String toString(Field f) {
63 return "field " + f.getDeclaringClass().getName() + "."
64 + f.getName();
65 }
66 },
67 new Converter<Class>(Class.class) {
68 public String toString(Class c) {
69 return c.getName();
70 }
71 },
72 new Converter<Key>(Key.class) {
73 public String toString(Key k) {
74 return k.hasDefaultName()
crazyboblee0baa9fc2007-01-31 02:38:54 +000075 ? k.getType().toString()
76 : k.getType() + " named '" + k.getName() + "'";
crazyboblee235d0682007-01-31 02:25:21 +000077 }
78 }
79 );
80
81 static abstract class Converter<T> {
82
83 final Class<T> type;
84
85 Converter(Class<T> type) {
86 this.type = type;
87 }
88
89 boolean appliesTo(Object o) {
90 return type.isAssignableFrom(o.getClass());
91 }
92
93 String convert(Object o) {
94 return toString(type.cast(o));
95 }
96
97 abstract String toString(T t);
98 }
99}