Java Class New Instance newInstance(Class cls)

Here you can find the source of newInstance(Class cls)

Description

Creates a new instance of the class.

License

Open Source License

Parameter

Parameter Description
cls The class to instantiate.
T The type of the class.

Return

The newly instantiated object or null if the instantiation failed.

Declaration

@SuppressWarnings("unchecked")
public static <T> T newInstance(Class<T> cls) 

Method Source Code


//package com.java2s;
/*//from w w w  .  java  2s  . co m
 * AirBlock - Framework for Multi-Platform Minecraft-Plugins.
 * Copyright (C) 2014 stux!
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.lang.reflect.*;

public class Main {
    /**
     * Creates a new instance of the class.
     * @param cls The class to instantiate.
     * @param <T> The type of the class.
     * @return The newly instantiated object or {@code null} if the instantiation failed.
     */
    @SuppressWarnings("unchecked")
    public static <T> T newInstance(Class<T> cls) {
        Constructor constructor;
        try {
            constructor = cls.getConstructor();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            return null;
        }

        if (!constructor.isAccessible())
            constructor.setAccessible(true);

        try {
            return (T) constructor.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
            return null;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return null;
        } catch (InvocationTargetException e) {
            e.getCause().printStackTrace();
            return null;
        }
    }
}

Related

  1. newInstance(Class clazz)
  2. newInstance(Class clazz)
  3. newInstance(Class clazz)
  4. newInstance(Class clazz, Class[] argumentTypes, Object[] arguments)
  5. newInstance(Class clazz, Class[] parameterTypes, Object[] initargs)
  6. newInstance(Class cls)
  7. newInstance(Class cls, Object... args)
  8. newInstance(Class clz, Class argType, K arg)
  9. newInstance(Class componentType, int size)