Here you can find the source of newInstance(final Class
@SuppressWarnings("unchecked") public static <T> T newInstance(final Class<T> clazz)
//package com.java2s; /*//from w w w. j a va 2 s. c o m * Copyright 2002-2008 the original author or authors. * * 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. */ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; public class Main { @SuppressWarnings("unchecked") public static <T> T newInstance(final Class<T> clazz) { if (clazz.isInterface()) { // Register Default Implmentation for class,else ioc if (Map.class.equals(clazz)) { return (T) new LinkedHashMap(); } else if (List.class.equals(clazz)) { return (T) new ArrayList(); } else if (Set.class.equals(clazz)) { return (T) new LinkedHashSet(); } else if (Collection.class.equals(clazz)) { return (T) new ArrayList(); } } try { return clazz.newInstance(); } catch (final InstantiationException e) { e.printStackTrace(); } catch (final IllegalAccessException e) { e.printStackTrace(); } return null; } public static Object newInstance(final Type type) { final Class<?> clazz = getRawClass(type); return newInstance(clazz); } @SuppressWarnings("unchecked") public static <T> Class<T> getRawClass(final Type type) { if (type instanceof Class) { return (Class<T>) type; } else if (type instanceof ParameterizedType) { return (Class<T>) ((ParameterizedType) type).getRawType(); } return null; } }