Java Reflection Constructor Invoke invokeConstructor(Class objectClass, Class[] classes, Object... params)

Here you can find the source of invokeConstructor(Class objectClass, Class[] classes, Object... params)

Description

invoke Constructor

License

Open Source License

Declaration

public static Object invokeConstructor(Class<?> objectClass, Class<?>[] classes, Object... params) 

Method Source Code

//package com.java2s;
/**/*from   w ww  .  j  av  a 2s .  c om*/
 * Copyright 2008 Autentia Real Business Solutions S.L.
 * 
 * This file is part of autentia-util.
 * 
 * autentia-util is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 * 
 * autentia-util is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with autentia-util. If not, see <http://www.gnu.org/licenses/>.
 */

import java.lang.reflect.Constructor;

public class Main {

    public static Object invokeConstructor(Class<?> objectClass, Class<?>[] classes, Object... params) {
        Object result = null;

        Constructor<?> constructor;
        try {
            constructor = objectClass.getDeclaredConstructor(classes);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Exception obtaining the constructor for class '" + objectClass + "' with params=" + params, e);
        }

        boolean accessible = constructor.isAccessible();
        constructor.setAccessible(true);

        try {
            result = constructor.newInstance(params);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Exception invoking the constructor for class '" + objectClass + "' with params=" + params, e);
        } finally {
            constructor.setAccessible(accessible);
        }

        return result;
    }
}

Related

  1. invoke(Constructor constructor)
  2. invoke(Constructor constructor, Object... args)
  3. invoke(Constructor constructor, Object... args)
  4. invokeConstructor(Class clazz, Class[] paramTypes, Object[] params)
  5. invokeConstructor(Class clazz, Object... parameters)
  6. invokeConstructor(Class clazz, Class[] argTypes, Object[] args)
  7. invokeConstructor(Class cls)
  8. invokeConstructor(Class type, Object value)
  9. invokeConstructor(Constructor constructor, Object... arguments)