Here you can find the source of newInstance(String className)
Parameter | Description |
---|---|
className | class name |
public static <T> T newInstance(String className)
//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); } } }