Here you can find the source of invokeConstructor(final Class
Parameter | Description |
---|---|
clazz | The class on which to invoke the constructor. |
paramTypes | The parameter types. |
args | The argument types. |
T | The type of object to create. |
null
if an exception occurred.
@Nullable private static <T> T invokeConstructor(final Class<T> clazz, final Class<?>[] paramTypes, final Object... args)
//package com.java2s; /*/*w w w.ja v a2s . c o m*/ * Copyright ? 2015-2016 * * This file is part of Spoofax for IntelliJ. * * 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 javax.annotation.Nullable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class Main { /** * Invokes a constructor. * * @param clazz The class on which to invoke the constructor. * @param paramTypes The parameter types. * @param args The argument types. * @param <T> The type of object to create. * @return The resulting object; or <code>null</code> if an exception occurred. */ @Nullable private static <T> T invokeConstructor(final Class<T> clazz, final Class<?>[] paramTypes, final Object... args) { assert paramTypes.length == args.length; @Nullable T obj = null; try { if (paramTypes.length > 0) { final Constructor<T> constructor = clazz.getConstructor(paramTypes); obj = constructor.newInstance(args); } else { obj = clazz.newInstance(); } } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { // Ignore. } return obj; } }