Here you can find the source of coerce(Object value, Class
@SuppressWarnings({ "unchecked" }) public static <T> T coerce(Object value, Class<T> clazz)
//package com.java2s; /*//from w ww .j a v a 2 s. c om Copyright (c) 2012 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class Main { @SuppressWarnings({ "unchecked" }) public static <T> T coerce(Object value, Class<T> clazz) { if (clazz.isAssignableFrom(value.getClass())) { return (T) value; } if (value instanceof String) { String str = (String) value; if (clazz.equals(Double.class)) { return (T) Double.valueOf(Double.parseDouble(str)); } if (clazz.equals(Float.class)) { return (T) Float.valueOf(Float.parseFloat(str)); } if (clazz.equals(Long.class)) { return (T) Long.valueOf(Long.parseLong(str)); } if (clazz.equals(Integer.class)) { return (T) Integer.valueOf(Integer.parseInt(str)); } if (clazz.equals(Boolean.class)) { return (T) Boolean.valueOf(Boolean.parseBoolean(str)); } } else { throw new IllegalArgumentException( "Cannot convert value of " + value.getClass() + " to class = " + clazz.getName()); } return (T) value; } public static Double parseDouble(String key, String doubleStr) { try { return Double.parseDouble(doubleStr); } catch (NumberFormatException e) { throw new IllegalArgumentException(key + "is not a double", e); } } public static Long parseLong(String key, String intStr) { try { return Long.parseLong(intStr); } catch (NumberFormatException e) { throw new IllegalArgumentException(key + "is not an long Integer", e); } } public static Integer parseInt(String key, String intStr) { try { return Integer.parseInt(intStr); } catch (NumberFormatException e) { throw new IllegalArgumentException(key + "is not an Integer", e); } } }