Here you can find the source of newInstance(Class
Parameter | Description |
---|---|
IllegalAccessException | an exception |
InstantiationException | an exception |
public static <T> T newInstance(Class<T> type) throws InstantiationException, IllegalAccessException
//package com.java2s; //License from project: Apache License public class Main { /**//from w w w. ja v a 2 s . co m * A helper method to create a new instance of a type using the default * constructor arguments. * @throws IllegalAccessException * @throws InstantiationException */ public static <T> T newInstance(Class<T> type) throws InstantiationException, IllegalAccessException { return type.newInstance(); } /** * A helper method to create a new instance of a type using the default * constructor arguments. * @throws IllegalAccessException * @throws InstantiationException */ public static <T> T newInstance(Class<?> actualType, Class<T> expectedType) throws InstantiationException, IllegalAccessException { Object value = actualType.newInstance(); return cast(expectedType, value); } /** * Converts the given value to the required type or throw a meaningful exception */ @SuppressWarnings("unchecked") public static <T> T cast(Class<T> toType, Object value) { if (toType == boolean.class) { return (T) cast(Boolean.class, value); } else if (toType.isPrimitive()) { Class newType = convertPrimitiveTypeToWrapperType(toType); if (newType != toType) { return (T) cast(newType, value); } } try { return toType.cast(value); } catch (ClassCastException e) { throw new IllegalArgumentException( "Failed to convert: " + value + " to type: " + toType.getName() + " due to: " + e, e); } } /** * Converts primitive types such as int to its wrapper type like * {@link Integer} */ public static Class<?> convertPrimitiveTypeToWrapperType(Class<?> type) { Class<?> rc = type; if (type.isPrimitive()) { if (type == int.class) { rc = Integer.class; } else if (type == long.class) { rc = Long.class; } else if (type == double.class) { rc = Double.class; } else if (type == float.class) { rc = Float.class; } else if (type == short.class) { rc = Short.class; } else if (type == byte.class) { rc = Byte.class; } else if (type == boolean.class) { rc = Boolean.class; } } return rc; } }