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.gson; 18 19 import com.google.gson.internal.Primitives; 20 import java.lang.reflect.Constructor; 21 import java.lang.reflect.InvocationTargetException; 22 import java.lang.reflect.Method; 23 24 /** 25 * Handles type conversion from some object to some primitive (or primitive 26 * wrapper instance). 27 * 28 * @author Joel Leitch 29 */ 30 final class PrimitiveTypeAdapter { 31 32 @SuppressWarnings("unchecked") adaptType(Object from, Class<T> to)33 public <T> T adaptType(Object from, Class<T> to) { 34 Class<?> aClass = Primitives.wrap(to); 35 if (Primitives.isWrapperType(aClass)) { 36 if (aClass == Character.class) { 37 String value = from.toString(); 38 if (value.length() == 1) { 39 return (T) (Character) from.toString().charAt(0); 40 } 41 throw new JsonParseException("The value: " + value + " contains more than a character."); 42 } 43 44 try { 45 Constructor<?> constructor = aClass.getConstructor(String.class); 46 return (T) constructor.newInstance(from.toString()); 47 } catch (NoSuchMethodException e) { 48 throw new JsonParseException(e); 49 } catch (IllegalAccessException e) { 50 throw new JsonParseException(e); 51 } catch (InvocationTargetException e) { 52 throw new JsonParseException(e); 53 } catch (InstantiationException e) { 54 throw new JsonParseException(e); 55 } 56 } else if (Enum.class.isAssignableFrom(to)) { 57 // Case where the type being adapted to is an Enum 58 // We will try to convert from.toString() to the enum 59 try { 60 Method valuesMethod = to.getMethod("valueOf", String.class); 61 return (T) valuesMethod.invoke(null, from.toString()); 62 } catch (NoSuchMethodException e) { 63 throw new RuntimeException(e); 64 } catch (IllegalAccessException e) { 65 throw new RuntimeException(e); 66 } catch (InvocationTargetException e) { 67 throw new RuntimeException(e); 68 } 69 } else { 70 throw new JsonParseException("Can not adapt type " + from.getClass() + " to " + to); 71 } 72 } 73 } 74