Here you can find the source of newInstance(Class
Parameter | Description |
---|---|
T | template type |
theClass | a parameter |
public static <T> T newInstance(Class<T> theClass)
//package com.java2s; /******************************************************************************* * Copyright 2012 Internet2/* w w w . jav a 2 s . c om*/ * * 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.Constructor; import java.lang.reflect.Modifier; public class Main { /** * Construct a class * @param <T> template type * @param theClass * @return the instance */ public static <T> T newInstance(Class<T> theClass) { try { return theClass.newInstance(); } catch (Throwable e) { if (theClass != null && Modifier.isAbstract(theClass.getModifiers())) { throw new RuntimeException("Problem with class: " + theClass + ", maybe because it is abstract!", e); } throw new RuntimeException("Problem with class: " + theClass, e); } } /** * Construct a class * @param <T> template type * @param theClass * @param allowPrivateConstructor true if should allow private constructors * @return the instance */ public static <T> T newInstance(Class<T> theClass, boolean allowPrivateConstructor) { if (!allowPrivateConstructor) { return newInstance(theClass); } try { Constructor<?>[] constructorArray = theClass .getDeclaredConstructors(); for (Constructor<?> constructor : constructorArray) { if (constructor.getGenericParameterTypes().length == 0) { if (allowPrivateConstructor) { constructor.setAccessible(true); } return (T) constructor.newInstance(); } } //why cant we find a constructor??? throw new RuntimeException( "Why cant we find a constructor for class: " + theClass); } catch (Throwable e) { if (theClass != null && Modifier.isAbstract(theClass.getModifiers())) { throw new RuntimeException("Problem with class: " + theClass + ", maybe because it is abstract!", e); } throw new RuntimeException("Problem with class: " + theClass, e); } } }