blob: 29d00eaabc8dad288577f944f35f02c74061a744 [file] [log] [blame]
Jesse Wilson109c1282009-12-08 13:45:25 -08001/**
2 * Copyright (C) 2009 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
17package com.google.caliper;
18
Jesse Wilsonf062bf42010-01-13 17:12:18 -080019import com.google.common.collect.ImmutableMap;
20import java.lang.reflect.Method;
Jesse Wilson109c1282009-12-08 13:45:25 -080021import java.lang.reflect.Type;
Jesse Wilsonf062bf42010-01-13 17:12:18 -080022import java.util.Map;
Jesse Wilson109c1282009-12-08 13:45:25 -080023
24/**
25 * Convert objects to and from Strings.
26 */
Jesse Wilsonf062bf42010-01-13 17:12:18 -080027final class TypeConverter {
28 private TypeConverter() {}
Jesse Wilson109c1282009-12-08 13:45:25 -080029
Jesse Wilsonf062bf42010-01-13 17:12:18 -080030 public static Object fromString(String value, Type type) {
31 Class<?> c = wrap((Class<?>) type);
32 try {
33 Method m = c.getMethod("valueOf", String.class);
34 return m.invoke(null, value);
35 } catch (Exception e) {
36 throw new UnsupportedOperationException(
37 "Cannot convert " + value + " of type " + type, e);
38 }
39 }
40
41 // safe because both Long.class and long.class are of type Class<Long>
Jesse Wilson109c1282009-12-08 13:45:25 -080042 @SuppressWarnings("unchecked")
Jesse Wilsonf062bf42010-01-13 17:12:18 -080043 private static <T> Class<T> wrap(Class<T> c) {
44 return c.isPrimitive() ? (Class<T>) PRIMITIVES_TO_WRAPPERS.get(c) : c;
Jesse Wilson109c1282009-12-08 13:45:25 -080045 }
46
Jesse Wilsonf062bf42010-01-13 17:12:18 -080047 private static final Map<Class<?>, Class<?>> PRIMITIVES_TO_WRAPPERS
48 = new ImmutableMap.Builder<Class<?>, Class<?>>()
49 .put(boolean.class, Boolean.class)
50 .put(byte.class, Byte.class)
51 .put(char.class, Character.class)
52 .put(double.class, Double.class)
53 .put(float.class, Float.class)
54 .put(int.class, Integer.class)
55 .put(long.class, Long.class)
56 .put(short.class, Short.class)
57 .put(void.class, Void.class)
58 .build();
Jesse Wilson109c1282009-12-08 13:45:25 -080059}