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 create a new instance for

Return

the new instance, or null in case of an error

Declaration

public static Object newInstance(Class cls) 

Method Source Code

//package com.java2s;
/*//  ww  w.j a  v  a2  s .  c  o m
 *   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/>.
 */

public class Main {
    /**
     * Creates a new instance of the class represented by this object.
     *
     * @param o      the object to create a new instance for
     * @return      the new instance, or null in case of an error
     */
    public static Object newInstance(Object o) {
        if (o != null)
            return newInstance(o.getClass());
        else
            return null;
    }

    /**
     * Creates a new instance of the class.
     *
     * @param cls      the class to create a new instance for
     * @return      the new instance, or null in case of an error
     */
    public static Object newInstance(Class cls) {
        Object result;

        try {
            result = cls.newInstance();
        } catch (Exception e) {
            System.err.println("Error creating new instance for " + cls.getName() + ":");
            e.printStackTrace();
            result = null;
        }

        return result;
    }
}

Related

  1. newInstance(Class clazz)
  2. newInstance(Class clazz)
  3. newInstance(Class clazz)
  4. newInstance(Class clazzName)
  5. newInstance(Class cls)
  6. newInstance(Class cmdClass)
  7. newInstance(Class constructorClass, Object[] parameters)
  8. newInstance(Class klass)
  9. newInstance(Class targetClass)