Java Class New Instance newInstance(String className)

Here you can find the source of newInstance(String className)

Description

New target Object instance using the given Class name

License

LGPL

Parameter

Parameter Description
className class name

Return

new Object instance

Declaration

public static <T> T newInstance(String className) 

Method Source Code


//package com.java2s;
/*/*from   w w  w.j  a  va  2s.  c  om*/
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later.
 * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
 */

import java.lang.reflect.Constructor;

import java.lang.reflect.InvocationTargetException;

import java.util.function.Supplier;

public class Main {
    /**
     * New target Object instance using the given arguments
     *
     * @param constructorSupplier constructor supplier
     * @param args Constructor arguments
     *
     * @return new Object instance
     */
    public static <T> T newInstance(Supplier<Constructor<T>> constructorSupplier, Object... args) {
        try {
            Constructor constructor = constructorSupplier.get();
            constructor.setAccessible(true);
            return (T) constructor.newInstance(args);
        } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
            throw new IllegalArgumentException("Constructor could not be called", e);
        }
    }

    /**
     * New target Object instance using the given Class name
     *
     * @param className class name
     *
     * @return new Object instance
     */
    public static <T> T newInstance(String className) {
        try {
            return (T) Class.forName(className).newInstance();
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
            throw new IllegalArgumentException("Constructor could not be called", e);
        }
    }
}

Related

  1. newInstance(String className)
  2. newInstance(String className)
  3. newInstance(String className)
  4. newInstance(String className)
  5. newInstance(String className)
  6. newInstance(String className)
  7. newInstance(String className)
  8. newInstance(String className)
  9. newInstance(String className)